Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointers and arrays/ 'sizeof' operator [duplicate]

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?

like image 780
SystemFun Avatar asked Jan 12 '13 22:01

SystemFun


2 Answers

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.

like image 140
Carl Norum Avatar answered Oct 02 '22 21:10

Carl Norum


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.

like image 42
DiJuMx Avatar answered Oct 02 '22 20:10

DiJuMx