为什么数组的大小不一致取决于它在源代码中的位置

Why is the size of an array inconsisten depending on its location in the source code?

本文关键字:源代码 位置 不一致 数组 为什么 取决于      更新时间:2023-10-16

我可以声明animal_array1animal_array2。堆栈上的第一个,而第二个是…仍然在堆栈上,但这次声明为函数参数。下面是一个示例代码:

 #include <iostream>
 using namespace std;
 struct Animal
 {
 };
 void test(Animal animal_array2[10])
 {
     Animal animal_array1[10];
     if(sizeof(animal_array2) == sizeof(animal_array1))
         cout << "Both sizes are equal. That's expected!" << endl;
     else
         cout << "Mhhh sizes are *NOT* equal. That wasn't expected at all!" << endl;
 }
 int main()
 {
     Animal unused_var[10];
     test(unused_var);
 }

输出为:

 $./a.out 
 Mhhh sizes are *NOT* equal. That wasn't expected at all!

怎么可能呢?Gcc错误?或者这是标准行为?我们如何从相同的表观类型中得到如此拉伸的结果?

数组是C和c++中唯一不能按值传递的数据类型。因此,作为函数形参,数组衰变成指向数组第一个元素的指针(当声明并传递时)。

基本上就是:

void test(Animal animal_array2[10])

实际上是:

void test(Animal *animal_array2)

但是只能作为函数参数

和作为形参传递的数组:

test(unused_var);

衰变成指向数组第一个元素的指针:

test(&(unused_var[0]));

(作为旁注:但没有实际的解引用)

数组在传递给c++函数时将衰变成指针。通常,您要做的是将已知的大小作为单独的参数传递给函数。