我是 C++ 的新手,这是一个非常基本的问题。
在 C++ 中,只有两种创建动态数组的方法(读过一本书,如果我错了请纠正我)使用 new
运算符或malloc()
函数,取自 C。
当声明一个数组int array[size]
时,方括号[]
必须有一个const
.
但是在下面的代码中,size
是一个unsigned int
变量。
#include<iostream>
int main() {
using namespace std;
unsigned int size;
cout<<"Enter size of the array : ";
cin>>size;
int array[size]; // Dynamically Allocating Memory
cout<<"\nEnter the elements of the array\n";
// Reading Elements
for (int i = 0; i < size; i++) {
cout<<" :";
cin>>array[i];
}
// Displaying Elements
cout<<"\nThere are total "<<size<<" elements, as listed below.";
for (int j = 0; j < size; j++) {
cout<<endl<<array[j];
}
return 0;
}
虽然编译 g++ 没有抛出任何错误,而且程序运行完美。
问题 1: 这可能是另一种创建动态数组的方法吗?
问题 2:代码是否正确?
问题 3:如果 []
只能包含 const
,为什么代码可以工作?
最佳答案
- 正确,您发现了a
gcc
extension .这在 C 中已经允许了很长时间,但直到 C++14 才将其纳入 C++ 标准。 - 是的,代码是正确的,前提是您可以使用该语言的不可移植扩展。
- 符合标准的编译器也是如此。你可以告诉
gcc
您不想通过提供-std=c++98
使用扩展或-std=c++11
编译器标志。
如果在 C++ 中需要一个动态大小的数组,更好的方法是使用 std::vector<T>
.它为您提供了动态分配数组的灵 active ,并负责为您管理分配的内存。
关于c++ - 没有 new 的动态数组 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25474248/