Possible Duplicate: Stack pointer difference for char pointer and array
To illustrate my question:
int main(void){
int myary[20];
int *myaryPtr;
myaryPtr = myary;
sizeof(myary); // Will it return 80? Correct?
sizeof(myaryPtr); // Will it return 4? Correct?
return 0;
}
First off, is my assumption correct?
And then assuming my assumption is correct, what is the detailed explanation? I understand that my 20 element array is 80 bytes, but isn't the name myary
merely a pointer to the first element of the array? So shouldn't it also be 4?
Yes, your assumption is correct, assuming an int
and a pointer are both 4 bytes long on your machine.
And no, arrays aren't pointers. The array name sometimes decays into a pointer in certain contexts, but they aren't the same thing. There is a whole section of the comp.lang.c FAQ dedicated to this common point of confusion.
The size of the array is not stored in memory in either case, whether you declare it as int myArr[20]
or int* myArrPtr
.
What happens is that sizeof()
is replaced (by the compiler) with a constant value.
Therefore, because myArr
was specified with a fixed size prior to compilation, the compiler knows just how big the amount of memory allocated is. With myArrPtr
, you could dynamically allocate different array sizes, so only the size of the type is stored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With