C++:数组的大小在传递给函数后发生变化
c++: array's size changed after passed to a function
我是 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::vector
或std::array
,而不是普通的C样式数组。
根据您的程序:
int a_len = sizeof(foo);
int e_len = sizeof(foo[0]);
是一个function
variable
,因此compiler
可以将其解释为array
,因为它与declared
和initialized
的函数位于同一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)
希望这能帮助您理解。
相关文章:
- 为什么向量内部的指针在从函数返回时会发生变化?
- 我正在将一个 std::string 传递给一个 boost 函数,该函数对该类型进行常量引用,但该值发生了变化
- 为什么使用默认构造函数"{}"而不是"= default"存在性能变化?
- 当对象传递给成员函数时,成员函数的行为会发生变化?
- C 变化函数语法
- 派生类中函数参数变化的虚函数按常量类型在"function parameter"会破坏虚拟机制吗?
- 整数变量的值在传递给 c++ 中的函数后发生变化
- 为什么值会发生变化,尽管函数被定义为常量
- 将模板变化函数及其参数传递到一个函数
- 这个树搜索功能让我发疯.它返回 NULL,但不知何故主函数中的值发生了变化
- 当在函数内部使用静态变量时,输出会发生变化,该函数在c++中返回引用
- C 传递功能,将参数数量变化为参数到其他函数
- C/C 中POW()函数的实现是否随平台或编译器而变化
- C++:数组的大小在传递给函数后发生变化
- 链表头指针在传递给函数c++时发生变化
- 函数输入变化
- 为什么我的向量在通过构造函数传递后会发生变化
- 由于在 g++ 4.4.7 的 std::vector 中使用内联函数而导致精度变化C++ 32 位20120313
- 在递归函数中打印一次变量,该变量会随着每次递归而不断变化
- 成员函数的可访问性似乎随 SFML 中的范围而变化,C++ Xcode 中也是如此