需要一些帮助来解决“将元素从字符串数组传递给线程”的问题。我的代码是在这个文本之后。我在main
函数中声明了一个字符串数组,然后将该数组的一个元素传递给一个线程。在线程中我将它转换回char *类型然后打印,但它会打印垃圾值。将不胜感激解决方案:
#include <stdio.h>
#include <pthread.h>
void *agent(void *);
int main(int argc, char *argv[]) {
int i;
pthread_t agent_t[3];
char *agent_colour[3] = {"Red","White","Brown"};
for(i = 0 ; i <= 2 ; i++) {
pthread_create(&agent_t[i], 0, agent, &agent_colour[i]);
}
for(i = 0 ; i <= 2 ; i++) {
pthread_join(agent_t[i], NULL);
}
return 0;
}
void *agent(void *arg) {
char *colour = (char*)arg;
int x;
srand(time(NULL));
x = rand() % 5 + 1;
sleep(x);
printf("\n My name is Agent %s\n", colour);
pthread_exit(NULL);
}
我的输出是:
My name is Agent � @
My name is Agent � @
My name is Agent � @
答案 0 :(得分:6)
试试这个:
pthread_create(&agent_t[i], 0, agent, agent_colour[i]);
答案 1 :(得分:1)
pthread_create
电话
&agent_colour[i]
你只想传递字符串
agent_colour[i]
答案 2 :(得分:0)
agent_colour是一个指针数组。所以只需在pthread create中传递这样的agent_colour [i]。