I am attempting to pass an array as an argument to a function in a new thread using pthread_create, is this possible? I have an array of integers and a calculate average method that is called from the create thread method but I cannot seem to pass my array into the method correctly. Here is my code: int nums[];
int average;
int size = 0;
void *calcAvg(int *nums[]);
int main(int argc, char *argv[]){
/* initialize an array of the integers to be passed */
nums[argc - 1];
for(int i = 0; i < argc - 1; i++){
nums[i] = atoi(argv[i + 1]);
size++;
}
/* Thread Identifier */
pthread_t avgThread;
pthread_create(&avgThread, NULL, calcAvg, nums);
pthread_join(avgThread, NULL);
printf("average= %d", average);
}
void *calcAvg(int *nums[]){
int sum;
for(int i = 0; i < size; i++){
sum += nums[i];
}
average = sum / (size);
pthread_exit(0);
}
numsinmainis not even declared properly, it seems.void *thread_function(void *arg)— a function that takes a 'universal pointer' (pointer tovoid) as an argument and returns a pointer tovoid. YourcalcAvg()function doesn't match that, so the solution by michaeltang fixes that problem. There's no particular reason to usepthread_exit(0);at the end; were it my code, I'd usereturn 0;— but the net result is the same except that the compiler won't complain about not returning a value from a function that is supposed to do so.void *toint *is legitimate given that the input was originally anintarray, which is converted first to anintpointer (a pointer to the first element of the array) and then to avoidpointer to match the function prototype. Your declaration usingint *nums[]manages to use two levels of pointer where only one is required; you would have done better withint *numsorint nums[]— there are equivalent when used in a function declaration or definition (but only in that context — elsewhere, they are rather different).sizeandaverage. Given that your main thread goes to sleep while the only child thread is executing, there is no problem. If you had two or more child threads, you would need to worry about whether it was safe to use the variables. Given thatsizeis fixed once the threads start (so they'd only read it), then that would be OK. However, if multiple threads are accessingaverage, you really need a mutex or something similar to protect it from concurrent access.