Why is arr1 size less than arr2, am I missing something? Does it have to do something with malloc and stack, heap?
#include <malloc.h>
#include <stdio.h>
int main(void)
{
int length = 4;
int *arr1 = (int*)malloc(length*sizeof(int));
int arr2[length];
arr2[0] = 10;
arr2[1] = 20;
arr2[2] = 30;
arr2[3] = 40;
arr1 = arr2;
for (int i = 0; i<length; printf("%d\n", arr1[i++])) ;
printf("Size of arr %lu\n", sizeof(arr1));
printf("Size of arr2 %lu\n", sizeof(arr2));
printf("Size of int %lu", sizeof(int));
}
Output:
$ gcc -g new.cpp && ./a.out
10
20
30
40
Size of arr 8
Size of arr2 16
Size of int 4
I was expecting to have arr1 and arr2 both have 16 byte size.
The variable
arr1declared likehas the pointer type
int *while the variablearr2declared as a variable length arrayhas the type
int[4].So the expression
sizeof( arr1 )that is equivalent tosizeof( int * )yields the size of the pointer itself.Pay attention to that your program has a memory leak because a memory was allocated and its address was stored in the pointer
arr1and then the pointerarr1was reassignedThe array
arr2used as an expression in the above assignment statement is implicitly converted to a pointer to its first element. That is the above statement in fact is equivalent toAlso to output a value of the type
size_tyou should use conversion specification%zubecause the C Standard accepts that it is not necessary that the typeunsigned longis an alias for the typesize_t..From the C Standard (7.19 Common definitions <stddef.h>)
Also if you wil write for example
sizeof( arr2 + 0 )then again the expression will yield the size of a pointer because in this expressionarr2 + 0with the pointer arithmetic the arrayarr2is implicitly converted to a pointer to its first element.