I am trying to implement a program in which the program takes numbers from user in command line and calculate their average in the thread and prints that average in main. But always getting segmentation fault error.
#include<iostream>
#include<pthread.h>
#include <unistd.h>
using namespace std;
void *avg(void* ar )
{
int *p=(int *) ar;
int size=*p;
size--;
float sum=0;
for(int i=0;i<size;i++)
{
p++;
int y=*p;
sum=sum+y;
}
float *avg1;
*avg1=sum/size;
float *rt=avg1;
pthread_exit((void *) rt);
}
int main(int arg,char** argc )
{
int n=arg;
int arr[n];
arr[0]=n; //storing aaray size in first index of array
for(int i=1;i<n;i++)
{
int x=atoi(argc[i]);
arr[i]=x;
}
for(int i=1;i<n;i++)
cout<<arr[i]<<endl;
pthread_t t1,t2;
int x=pthread_create(&t1,NULL,&avg,(void*)arr);
if(x!=0)
{
cout<<"Error in Creating Thread\n";
exit(EXIT_FAILURE);
}
float *rt1;
pthread_join(t1,(void**)&rt1);
cout<<"AVG:"<<*rt1;
return 0;
}
When i ran the same code on another pc, it was working fine.