C – Determining the Size of an Array

arraysc++size

a simple question that bugs me.
Say I have an array defined in main like so int arr[5]. Now, if I'm still inside main and I set int i = sizeof(arr)/sizeof(arr[0]) then I is set to be 5, but if I pass the array as a function parameter and do the exact same calculation in this function, I get a different number. Why is that? At first I thought its because in a function arr is a pointer, but as far as I know arr is a pointer inside main too!

Also, if I do something very similar only I initialize the array dynamically, I get weird results:

int *arr = (int*) malloc(sizeof(int) * 5);
int length = sizeof(*arr) / sizeof(arr[0]);
printf("%d\n",length);

Here the output is 1. Any ideas why?
Thanks in advance!

Best Answer

C arrays don't store their own sizes anywhere, so sizeof only works the way you expect if the size is known at compile time. malloc() is treated by the compiler as any other function, so sizeof can't tell that arr points to the first element of an array, let alone how big it is. If you need to know the size of the array, you need to explicitly pass it to your function, either as a separate argument, or by using a struct containing a pointer to your array and its size.

Related Question