如何将元素从字符串数组传递给线程?

需要一些帮助来解决“将元素从字符串数组传递给线程”的问题。 我的代码是在这个文本之后。 我在main函数中声明了一个字符串数组,然后将一个数组元素传递给一个线程。 在线程中我将它转换回char *类型然后打印,但它打印垃圾值。 将不胜感激解决方案:

 #include  #include  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   @ 

试试这个:

 pthread_create(&agent_t[i], 0, agent, agent_colour[i]); 

这在pthread_create调用中是错误的

 &agent_colour[i] 

你只想传递字符串

 agent_colour[i] 

agent_colour是一个指针数组。 所以只需在pthread create中传递这样的agent_colour [i]即可。