Jeungwoo Park Jeungwoo Park - 2 months ago 10
C Question

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

#include<stdio.h>
#include<stdlib.h>

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));

free(arr1);

return 0;
}


Output

8
16


Why?

Answer

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.