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()
.