C++:数组的大小在传递给函数后发生变化

c++: array's size changed after passed to a function

本文关键字:函数 变化 数组 C++      更新时间:2023-10-16

我是 C++ 的新手,当我编写程序来测试如何将数组作为函数中的参数传递时,我编写了这个小程序:


#include <iostream>
using namespace std;
void pass_by_array(int a[]) {
int a_len = sizeof(a);
int e_len = sizeof(a[0]);
cout << "size of array in func: " << a_len << endl;
cout << "size of element in func: " << e_len << endl;
}
int main() {
int foo[] = {1, 8, 2, 7, 3, 6};
int a_len = sizeof(foo);
int e_len = sizeof(foo[0]);
cout << "size of array in main: " << a_len << endl;
cout << "size of element in main: " << e_len << endl;
pass_by_array(foo);
return 0;
}

这是我得到的结果:

size of array in main: 24
size of element in main: 4
size of array in func: 8
size of element in func: 4

那到底是怎么回事呢? 数组的大小变了?!

当您将数组传递给函数时,它会衰减为指向其第一个元素的指针。因此,sizeof(a)实际上为您提供了指向int的指针的大小。在您的计算机上,这似乎是 8。

如果要将数组传递给函数,以使数组仍然知道其大小,请使用std::vectorstd::array,而不是普通的C样式数组。

根据您的程序:

int a_len = sizeof(foo);
int e_len = sizeof(foo[0]);

是一个function variable,因此compiler可以将其解释为array,因为它与declaredinitialized的函数位于同一stack frame

对于您的程序: main()

当您将数组传递给另一个函数时

pass_by_array(foo);

它被转换为在接收函数的堆栈帧中定义的指针,并存储数组的地址。

因此,根据您的程序:

int a_len = sizeof(a);
int e_len = sizeof(a[0]); 

第一个语句将为您提供int* a的大小,即 sizeof (pointer)int按照compiler.由于指针可以用作数组a[0]因此它将为您提供sizeof(int)

希望这能帮助您理解。