为什么数组的大小不一致取决于它在源代码中的位置
Why is the size of an array inconsisten depending on its location in the source code?
我可以声明animal_array1
和animal_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++函数时将衰变成指针。通常,您要做的是将已知的大小作为单独的参数传递给函数。
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 在Linux中哪里可以找到互斥、未来等的源代码
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如果编译的源代码是特定于它编译的硬件的,我们如何分发它
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 难以理解某些人解决IOI问题的源代码
- 非常量变量只读位置的赋值
- 如何定义更改car类中car位置的方法
- 使用迭代器时如何访问对象在向量中的位置?
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 在源代码树中放置第三方头文件的位置
- 无法找到在c++源代码中使用变量的位置
- 在Eclipse CDT的给定位置查看源代码中定义的所有宏
- OpenCV的源代码中的位置是大小类
- 为什么数组的大小不一致取决于它在源代码中的位置