我正在尝试编写一个简单的多线程程序,将命令行参数(一个 int)发送到一个函数,但我无法正确转换它。下面是我的程序片段,不包括不相关的代码。
int main(int argc, char **argv)
{
pthread_t thread1;
pthread_create(&thread1, NULL, simple_function, (void*)argv[1]);
pthread_join(thread1, NULL);
return EXIT_SUCCESS;
}
void* simple_function(void* num)
{
int n = *(int *)num;
printf(The number is: '%d', n);
n - 1;
...
}
我的程序实际做了什么:
命令行输入:14
预期的“printf”结果:14
实际的“printf”结果:1476408369
我的转换中缺少一些东西,但我不确定我应该将它转换成什么。编译过程中没有警告,任何帮助将不胜感激。
最佳答案
最突出的是 argv[1] 实际上是 (char *) 而不是 (int *)。您需要使用 atoi 之类的方法将字符串转换为数值。
void* simple_function(void* val)
{
char * c = (char *)val;
int n = atoi(c);
printf(The number is: '%d', n);
n - 1;
...
}
注意我还没有实际测试上面的代码,因为我目前无法访问 C 编译器
关于c - C中多线程的整数转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21177705/