Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)
I’m learning how to create a dynamic array in C, but have come across an issue I can’t figure out.
If I use the code:
int num[10];
for (int i = 0; i < 10; i++) {
num[i] = i;
}
printf("sizeof num = %li\n sizeof num[0] = %li", sizeof(num), sizeof(num[0]));
I get the output:
sizeof num = 40
sizeof num[0] = 4
This is what I’d expect to happen. However if I malloc the size of the array like:
int *num;
num = malloc(10 * sizeof(int));
for (int i = 0; i < 10; i++) {
num[i] = i;
}
printf("sizeof num = %li\n sizeof num[0] = %li", sizeof(num), sizeof(num[0]));
Then I get the output:
sizeof num = 8
sizeof num[0] = 4
I’m curious to know why the size of the array is 40 when I use the fixed length method, but not when I use malloc().
In the second case,
numis not an array, is a pointer.sizeofis giving you the size of the pointer, which seems to be 8 bytes on your platform.There is no way to know the size of a dynamically allocated array, you have to save it somewhere else.
sizeoflooks at the type, but you can’t obtain a complete array type (array type with a specified size, like the typeint[5]) from the result ofmallocin any way, andsizeofargument can’t be applied to an incomplete type, likeint[].