C++ Size of Array [duplicate]

社会主义新天地 提交于 2019-11-30 09:14:59

问题


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;
    }

回答1:


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;
}



回答2:


 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])



回答3:


Your program below is similar to the next one.

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

Program below prints the size of pointer.

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



回答4:


Arrays are simply pointers to an arbitrary amount of memory. If you do sizeof(array) it will return the size of a pointer - 4 bytes on 32 bit systems, and 8 bytes on 64 bit systems (if the program is compiled as 64 bit).

This is the same reason that you have to null-terminate your strings in c/c++ - to denote the end of the array.

Simply put, you have the keep track of the size of your arrays yourself. If you allocate an array of 40 bytes, you have to make sure you never access the array above the 40th index (ie. array[39]).

Hope this helps.



来源:https://stackoverflow.com/questions/9509829/c-size-of-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!