I filled up my array with the following elements:
91.54
-96.58
-5.14
-78.25
15.33
89.34
-12.76
-92.56
38.21
36.11
-43.83
48.39
79.57
34.34
-26.07
-10.47
54.37
9.06
-67.17
53.83
-8.13
89.71
85.77
-68.44
-88.22
-86.24
-5.44
53.32
75.62
51.08
-80.42
91.94
33.5
-29.44
70.33
70.56
-66.75
10.41
92.84
-33.14
-0.34
The last element of my array is the sum of all of these float values.
And I want to print the number of elements with the sizeof technique.
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *f = fopen("floats.txt", "r");
float *V, num, sum = 0;
int i = 0;
V = (float *)malloc(sizeof(float));
while(fscanf(f, "%f", &num) == 1){
i++;
V = (float *)realloc(V, i*sizeof(float));
V[(i-1)] = num;
sum += num;
}
i++;
V = (float *)realloc(V, i*sizeof(float));
V[(i-1)] = sum;
/*printf("%f\n", soma);
printf("%f\n", V[(i-1)]);
printf("%f\n", size);*/
printf("%ld\n", sizeof(V)/sizeof(V[0]));
printf("Sum = %f\n", V[sizeof(V)/sizeof(V[0]) -1]);
return 0;
}
The number of elements must be 41 but it is printing 2 and the Sum must be 375.779999 the last element stored in the array.
Why is this printing 2 instead of 41? That is my main question!