【发布时间】:2014-02-08 16:09:38
【问题描述】:
在解决“将元素从字符串数组传递到线程”的问题时需要一些帮助。我的代码在此文本之后。我在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 � @
【问题讨论】:
-
void *之间有太多多余的演员表。此外,字符串文字应声明为const char *,而不是char *。
标签: c arrays string multithreading