[英]Integer Casting Issue with Multi-threading in C
I am trying to write a simple multi-threaded program that sends a command line argument (an int) to a function, but I am having trouble converting it properly. 我正在尝试编写一个简单的多线程程序,该程序将命令行参数(int)发送给函数,但是我无法正确转换它。 Below is a snippet of my program excluding irrelevant code.
以下是我程序的摘录,不包括无关代码。
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;
...
}
What my program actually does: 我的程序实际做什么:
Command line input: 14 命令行输入:14
Expected 'printf' result: 14 预期的“ printf”结果:14
Actual 'printf' result: 1476408369 实际的'printf'结果:1476408369
There is something missing in my conversion but I am not sure what I should convert it to. 转换中缺少一些内容,但是我不确定该将其转换为什么。 There are no warnings during compilation, any help would be greatly appreciated.
编译过程中没有警告,不胜感激。
The main thing that stands out is that argv[1] is actually a (char *) not an (int *). 最主要的是argv [1]实际上是(char *)而不是(int *)。 You need to convert the string into a numeric value using something like atoi.
您需要使用atoi之类的将字符串转换为数值。
void* simple_function(void* val)
{
char * c = (char *)val;
int n = atoi(c);
printf(The number is: '%d', n);
n - 1;
...
}
Note i have not actually tested the above code as i don't currently have access to a C compiler 请注意,由于我目前无法使用C编译器,因此我尚未实际测试上述代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.