Passing Array as argument to a new thread in C

arrays, c, multithreading

Solution

there is lots of problem in your code, i fix some to compile hope it will help

compile: gcc -o main main.c -lpthread

execute: ./main 2 5

output: 3

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

int average;

int size = 0;


void *calcAvg(void *arg);
int main(int argc, char *argv[]){
  /* initialize an array of the integers to be passed */
  int *nums = (int*)malloc((argc - 1)*sizeof(int));
  int i = 1;
  for(i = 1; i < argc ; i++){
    nums[i-1] = atoi(argv[i]);
    size++;
  }

  /* Thread Identifier */
  pthread_t avgThread;

  pthread_create(&avgThread, NULL, calcAvg, (void*)nums);

  pthread_join(avgThread, NULL);
  printf("average = %d \n",average);
  free(nums);

}
void *calcAvg(void *arg){
  int *val_p = (int *) arg;
  int sum = 0;
  int i = 0;
  for( i = 0; i < size; i++){
    sum += val_p[i];
  }
  average = sum / (size);
  pthread_exit(0);
}

Problem

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); } ```

Original source