asdf asdf - 14 days ago 6
C Question

Passing an array to pthread_create

So i was trying to make a program that creates a thread in c whose job is to find the maximum of 2 given numbers. The first program that i wrote (named askisi.c) was the following:

#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>

int max;

void *max_of_two(void *param);

int main(int argc , char *argv[])
{
pthread_t tid;

pthread_attr_t attr;

if (argc != 3)
{
fprintf(stderr,"You have to give 2 numbers... \n");
return -1;
}

pthread_attr_init(&attr);

pthread_create(&tid,&attr,max_of_two,argv);
pthread_join(tid,NULL);
printf("max = %d\n",max);
}

void *max_of_two(void *param)
{
if(atoi(*param[1]) >= atoi(*param[2]))
max = atoi(*param[1]);
else
max = atoi(*param[2]);
pthread_exit(0);
}


But using gcc in Linux i got these errors:
enter image description here

Now after a lot of research i found that my the function
max_of_two
should be written like this:

void *max_of_two(void *param)
{
char **arguments = (char**)param;

if(atoi(arguments[1]) >= atoi(arguments[2])){
max = atoi(arguments[1]);}
else
max = atoi(arguments[2]);
pthread_exit(0);
}


The first problem is that i didn't find any explanation on why my first program didn't work. The second one is that i didn't find an understandable explanation on what the instruction
char **arguments = (char**)param;
actually does.

Answer

void is not a real type, and in that context it means the function expect any type and its up to the programmer to decide which is done with casting.

So by doing char **arguments = (char**)param; you casted param into char ** and assigned that cast to the variable arguments.

Comments