I am completing an assignment that is helping me understand the use of pointers. I feel like I have a good grasp except when it comes to returning the pointer from a function. Here is the code I'm having trouble with:
#include <stdlib.h>
#include <stdio.h>
//#include <time.h>
double *ptr;
double * userallocate(double numbers)
{
if (numbers < 1000000)
{
ptr = malloc(sizeof(double)*numbers);
return ptr;
}
else
{
printf("You have allocated too many numbers... SHAME\n");
exit(0);
}
}
double * gendata(double *ptr, double numbers)
{
int i;
for (i=0;i<numbers;i++)
ptr[i] = rand()/RAND_MAX;
return ptr;
}
void average(double numbers)
{
int i;
double sum, average;
for (i=0;i<numbers;i++)
sum+=ptr[i];
average = sum/numbers;
printf("%f,",sum);
printf("We have averaged %d random numbers for you.\n The average is %f",(int) numbers,average);
}
int main(int argc, char *argv[])
{
double num;
if (argc !=2)
{
printf("Not enough arguments... SHAME\n");
exit(0);
}
num = atof(argv[1]);
userallocate(num);
gendata(ptr,num);
average(num);
getchar();
return 0;
}
The first function userallocate() is meant to create a buffer that contains space for double precision with the size determined by the command line argument. My code compiles but when I try to put random numbers into the buffer and average them I get 0.0000. I think there is a problem with the way I am returning the pointer in userallocate() and passing it to the other functions. Any help would be appreciated!
double *ptr;from line 5 in your code inside themainfunction, that is, together withdouble num;double *ptrinside main then I get a compiling errorerror: ‘ptr’ undeclared (first use in this function) ptr = malloc(sizeof(double)*numbers);as well as the other functions ^userallocatetoo. And also inaverage(as a parameter).double sumshould bedouble sum = 0userallocate()to main? I guess in my head I thought once its returned to main it would magically jump around to the other functions :-)