C++ 编译器的行为可能不同。由于 C++ 中的数组可以使用以下方法声明:
方法一:
int size;
cout << "Enter size of array: ";
cin >> size;
int x[size];
for (int i = 0; i < size; i++)
{
//cout << "x[" << i << "] = ";
x[i] = i + 1;
}
方法B
int size;
cout << "Enter size of array: ";
cin >> size;
int *x = new int[size];
for (int i = 0; i < size; i++)
{
//cout << "x[" << i << "] = ";
x[i] = i + 1;
}
通过在运行时 获取用户的输入,两者都可以正常工作。我知道,使用方法 B,我们必须像 delete [] x
一样删除 x
。
- 为什么要使用
int *x = new int[size];
,如果两者服务相同 目的? - 使用
new
有什么好处?
以下是我正在测试的代码片段:
#include<iostream>
using namespace std;
int main()
{
int size;
cout << "Enter size of array: ";
cin >> size;
//int *x = new int[size];
int x[size];
for (int i = 0; i < size; i++)
{
//cout << "x[" << i << "] = ";
x[i] = i + 1;
}
cout << endl << "Display" << endl;
for (int i = 0; i < size; i++)
{
cout << "x[" << i << "] = " << x[i] << endl;
}
return 0;
}
最佳答案
C++ 标准没有定义方法 A,但在 ISO C99 中是允许的,GCC 在 C++ 模式下也支持它。来自 https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html :
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.
我刚刚在这里找到了一些相关的讨论:Variable Length Arrays in C++14?
关于c++ - 静态与动态数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48866340/