C++ 数组大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9509829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:54:40  来源:igfitidea点击:

C++ Size of Array

c++arrayssizeof

提问by Shamim Ahmed

Possible Duplicate:
Sizeof array passed as parameter

可能重复:
Sizeof 数组作为参数传递

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

我对 C++ 中的 sizeof 运算符很愚蠢,你知道为什么它是 4 和 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;
    }

回答by Seth Carnegie

In main, the name arrayis 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.

在 中main,名称array是一个数组,因此您可以使用sizeof. 但是,数组在传递给函数时会衰减为指针,因此您可以sizeof(int*)进入函数内部。

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

请注意,以参数的形式T arg[]完全相同一样走的是自变量T* arg。所以你的函数完全等同于

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

回答by iammilind

 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:

如果您打算传递数组本身,那么 C++ 提供您通过引用传递它:

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

Now,

现在,

sizeof(arg) == sizeof(int[3])

回答by kamae

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
}

回答by Gogeta70

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

数组只是指向任意数量内存的指针。如果您执行 sizeof(array) 它将返回指针的大小 - 在 32 位系统上为 4 个字节,在 64 位系统上为 8 个字节(如果程序编译为 64 位)。

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

这与您必须在 c/c++ 中以空值终止字符串的原因相同 - 以表示数组的结尾。

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

简而言之,您可以自己跟踪数组的大小。如果分配 40 个字节的数组,则必须确保永远不会访问第 40 个索引以上的数组(即数组 [39])。

Hope this helps.

希望这可以帮助。