Jeungwoo Park Jeungwoo Park - 1 year ago 80
C Question

Why the size of malloc-ed array and non-malloced array are different?


int main (int argc, char *argv[]) {

int* arr1 = (int*)malloc(sizeof(int)*4);
int arr2[4];

printf("%d \n", sizeof(arr1));
printf("%d \n", sizeof(arr2));


return 0;




Answer Source

Arrays are not pointers.

In your code, arr1 is a pointer, arr2 is an array.

Type of arr1 is int *, whereas, arr2 is of type int [4]. So sizeof produces different results. Your code is equivalent to

sizeof (int *);
sizeof (int [4]);

That said, sizeof yields the result of type size_t, so you should be using %zu to print the result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download