Because an "array" or an array name is simply a pointer that points to the "start point" of a block of data, how does the sizeof operator return the size of an array? I know that this is determined at run time.
int arr[10]; //Allocate enough memory to store 10 ints and make arr a pointer to the first address.
This question arises because we cannot determine the size of a malloc-ed chunk of memory using the operator. My understanding is that a "normal" array is same as malloc-ed memory, except for the use of the heap.
I am not able to understand why a non-heap array and heap array behave differently.
While an array name is used as a pointer in pointer arithmetic and when it is a function argument, an array is not a pointer. It is its own type. Loosely speaking, the
sizeofoperator cannot tell you the size of an object you would not know at compiler time. (See the note on VLAs at the end.) The size of a C array like inis known at compile time. The
sizeofoperator can report the size ofarrbecausearris set as a contiguous chunk of ten integers. It is part of its 'type', again, loosely speaking of 'type'.When you
mallocan array, what you get is a pointer to a yet-to-be determined chunk of heap memory. You cannot obviously know the size without analyzing the parameter ofmallocat compile time. The only way the compiler could do that would be to deeply analyze your program and figure it out. Often, that's completely impossible of course, because dynamic allocation will depend on the user.VLAs are a special case. The
sizeofoperator will calculate the size at runtime (C99 and later I believe). There are futher caveats that you can read about here.