gpt4 book ai didi

C- Linux- 创建线程并传入缓冲区

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:03:39 24 4
gpt4 key购买 nike

用户传入输入,这个输入存储在argv[2]中。我将这个值存储到缓冲区中,然后尝试通过我的 pthread_create 函数将该值传递给另一个函数。但是,这会扭曲缓冲区的值。

我传入的输入可能是“Hello”之类的东西,然后当它在“printFiles”函数中打印时,它是乱码。我该如何解决这个问题?

void *printFiles(void *file);

int main(int argc, char **argv)

{
pthread_t thread;

char *store = argv[2];

char *buffer = (malloc(500));

strcpy(buffer, store);

pthread_create(&thread, NULL, printFiles, (void *)&buffer);
pthread_join(&thread, NULL);
return 0;


}

void *printFiles(void *file)
{
printf("%s\n", file);

}

最佳答案

buffer 已经是一个指针。当你这样做时,你给线程一个指向指针的指针,然后你将它作为函数中的一个指针来处理:

pthread_create(&thread, NULL, printFiles, (void *)&buffer);

只需将指针传递给线程:

pthread_create(&thread, NULL, printFiles, (void *)buffer);

关于C- Linux- 创建线程并传入缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50733396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com