似乎记得 C++ 中的静态数组只能从 const 表达式初始化,但如果你写:
#include <iostream>
int main() {
int n;
std::cin >> n;
int a[n];
std::cout << sizeof(a);
return 0;
}
该程序成功编译(gcc C++17)并打印 n * sizeof(int)。 但为什么会这样呢?
最佳答案
Variable-length arrays不属于标准的一部分。它们可以作为编译器扩展出现,GCC 就是这种情况。编译时您可能会收到以下警告:
warning: ISO C++ forbids variable length array 'a' [-Wvla]
当应用于数组时,sizeof运算符返回整个数组的大小,即基础类型的大小乘以元素数。引用文献指出,我的重点是:
The size of each VLA instance does not change during its lifetime, but on another pass over the same code, it may be allocated with a different size.
标题为 6.19 Arrays of Variable Length 的 GCC 官方文档状态:
These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.
话虽如此,更喜欢 std::vector或std::array到原始(C 风格)数组。
关于C++ 静态数组与动态数组类似,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47968642/