Background: I am trying to clarify the mystery of pointers and dynamic memory allocation in C. I am trying to get several floating point inputs from user, store them in an array that is allocated dynamically and thus expanded to accommodate more values. Once the user enters 0, the loop terminates and the sum and average are calculated and printed. I am using Borland C 5.02
Problems:
1. The loop only works 4 times and then the 4th value is not stored!
2. If I replace x+i with x[i] and *(x+i-1) with x[i-1] I get “Floating point error: Stack Fault” “Abnormal Program termination.
int main(void)
{
float *x;
float sum=0;
float avg=0;
int i=0;
x=(float*)malloc(sizeof(float));
do
{
scanf("%f",x+i); //take input
i++;
x=(float*)realloc(x, i*sizeof(float)); //reallocate memory to store more values
if(x==NULL){printf("WARNING");}
printf("\n%f %p %d\n",*(x+i-1),x,i);
}while(*(x+i-1)!=0);
for(int j=0;j<i;j++)
{sum=sum+*(x+j);} // Sum all values
avg=sum/(i-1); //Find result, i is 1 bigger than number of values, ith value is 0
printf("\n\n%d sum: %f avg: %f ",i,sum,avg);
getch();
return 0;
}
Since
iis 0-based, your realloc should be:x=(float*)realloc(x, (i+1)*sizeof(float));