Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

array stays empty after assignment

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading