Reputation: 489
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. 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
Expected 'printf' result: 14
Actual 'printf' result: 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.
Upvotes: 0
Views: 76
Reputation: 131
The main thing that stands out is that argv[1] is actually a (char *) not an (int *). You need to convert the string into a numeric value using something like 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
Upvotes: 4