为什么会这样?
#include <iostream>
int main()
{
std::cout << "Enter a number: ";
int arraySize;
std::cin >> arraySize;
int array[arraySize];
for(int element : array)
{
element = 42;
std::cout << element << "\n";
}
std::cout << "Array size: " << sizeof(array) << "\n";
std::cout << "Element count: " << sizeof(array)/sizeof(int);
return 0;
}
我对 C++ 中动态内存分配的理解告诉我,需要它的一种情况是当您不知道在编译时需要分配的内存量时。在这个程序中,显然数组大小在程序编译时是未知的,而是动态的,因为它可以随着用户输入的值而改变。
这是一个在成功编译后运行的程序(没有警告和错误):
g++ 程序.cpp -std=c++11 -o 程序.exe
输入一个数字:12
42
42
42
42
42
42
42
42
42
42
42
42
数组大小:48
元素数:12
如您所见,创建了一个包含用户定义元素数量的数组, 每个都成功分配给 42,并通过 sizeof() 运算符证明存在。
为什么这不算动态内存分配和编译?
最佳答案
这种可变长度数组 (VLA) 的声明不是标准的:
int array[arraySize];
这一行用 g++ 编译的原因是编译器以 extension 的形式提供了这个功能。 :
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. 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.
关于c++ - C++中的动态内存分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45625350/