gpt4 book ai didi

c - 线程函数中的字符串参数

转载 作者:行者123 更新时间:2023-11-30 18:40:13 26 4
gpt4 key购买 nike

我在使用 pthread_create 将字符串传递给线程函数时遇到问题当我运行程序时,我得到奇怪的字符这是代码

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <sys/stat.h>

#define NTHREADS 3



void *myFun(void *ptr){
char * string;
string = (char *) ptr;
printf("string: %s\n", string);

return NULL;
}

int main(int argc, char *argv[]){
pthread_t threads[NTHREADS];
char* thread_args[NTHREADS];
int i;
char* string;
/* spawn threads */
for (i=0; i<NTHREADS; ++i){
string = "file1.txt";
thread_args[i] = string;
if(pthread_create(&threads[i], NULL, myFun, (void *) &thread_args[i]) != 0){
printf("Error creating thread\n");
exit(1);
}
}
/* Wait for threads to finish */
for (i=0; i<NTHREADS; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}

我可以传递一个 int ,而不会出现任何问题,就像我在代码中所做的那样,将其转换为 int ,但是对于 char 来说,它不起作用。

最佳答案

传递指针,而不是指针的地址。

if(pthread_create(&threads[i], NULL, myFun, (void *) thread_args[i])
^

关于c - 线程函数中的字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26835112/

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