When executing this c code
double *t = (double*) malloc(10 * sizeof(double));
printf("%lu\n", sizeof(t)/sizeof(t[0]);
for (int j = 0; j < 10; j++) {
t[j] = 5 * powl((j/10), 0.4);
printf("t_j: %lf\n", t[j]);
}
my array has only 0 stored and the size of my array is 1.
I am using Xcode and with thread sanitiser turned on, I get an error that malloc can’t allocate memory in vm-space.
malloc: nano zone abandoned due to inability to preallocate reserved vm space.
>Solution :
The variable t is declared as a pointer of the type double *.
So the expression sizeof(t)/sizeof(t[0]) is equivalent to sizeof( double * ) / sizeof( double ) and does not yield the number of elements in the allocated array.
Also in this statement
printf("%lu\n", sizeof(t)/sizeof(t[0]);
there is a typo. You need to add one more closing parenthesis.
And though the type size_t usually is defined as an alias for the type unsigned long it is more correctly to use the conversion specifier %zu instead of %lu because the C Standard allows in some implementations to define it as an alias for the type unsigned long long.
Also in this expression (j/10) there is used the integer arithmetic. So it always evaluates to 0. You should write (j/ 10.0) to convert operands of the expression to the common type double.