Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Size of Array [duplicate]

Tags:

c++

arrays

sizeof

Possible Duplicate:
Sizeof array passed as parameter

I am being stupid with this sizeof operator in c++, do you have any idea why it is 4 and 12 ?

 void function (int arg[]) {
        cout<<sizeof(arg)<<endl; // 4
    }

    int main ()
    {
        int array[] = {1, 2, 3};
        cout<<sizeof array<<endl; // 12
        function (array);
       return 0;
    }
like image 495
Shamim Ahmed Avatar asked Mar 01 '12 02:03

Shamim Ahmed


2 Answers

In main, the name array is an array so you get the size in bytes of the array with sizeof. However, an array decays to a pointer when passed to a function, so you get sizeof(int*) inside the function.

Be aware that taking an argument in the form of T arg[] is exactly the same as taking the argument as T* arg. So your function is the exact equivalent of

void function(int* arg) {
    cout << sizeof(arg) << endl;
}
like image 77
Seth Carnegie Avatar answered Oct 02 '22 04:10

Seth Carnegie


 void function (int arg[]) // or void function (int arg[N])

is equivalent to

 void function (int *arg)

thus,

sizeof(arg) == sizeof(int*)

If you intend to pass array itself, then C++ offers you to pass it by reference:

void function (int (&arg)[3])
              //   ^^^ pass by reference

Now,

sizeof(arg) == sizeof(int[3])
like image 21
iammilind Avatar answered Oct 02 '22 03:10

iammilind