I have a pointer of type double which is pointing to allocated memory using malloc, where I allocated 12 elements in the array:
double *y = (double*)malloc(sizeof(double) * 12);
My question is as follows. Say I allocated the memory in this way:
double *y2 = (double*)malloc(sizeof(double*) * 12);
What difference would it make when adding the * to the double in the size of bracket? Is there any significance to such a change? Am I calculating the size of a pointer to double rather than the size of a double? I am asking such a question because when I came to calculate fabs of y2[0] and say y2[0] was equal to -0.02 the answer was coming 0.00 whereas when I calculated the answer of fabs of y1[0] and y1[0] was equal to -0.02 the answer was 0.02.
sizeof (double)
is correct for the element size of an array of double
values. sizeof (double *)
would be the right value for an array of pointers to double
.
On most 64-bit architectures, both sizeof (double)
and sizeof (double *)
happen to be 8, but on most 32-bit architectures, sizeof (double)
is 8, but sizeof (double *)
is 4, so there is a difference.
If you get different results with sizeof (double *)
, it is likely because your allocation is too small and you encounter a heap buffer overflow and memory corruption as a result.