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!
The reason you see 0.0000
has nothing to do with pointers.
rand()
returns an int
, and RAND_MAX
, also an int
, will most likely be greater than the value returned by rand()
, so most of the time the result of the integer division is 0.
If you want floating point results, you will need to have one of the arguments to the division be a floating point type.
ptr[i] = rand()/(double)RAND_MAX;