我是 C++ 新手,这是一个非常基本的问题。
在 C++ 中,只有两种方法可以使用从 C 中获取的运算符或函数分配内存来创建动态数组(在书中阅读,如果我错了,请纠正我)。newmalloc()
声明数组时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;
}
Run Code Online (Sandbox Code Playgroud)
编译 g++ 时不会出错,而且程序运行完美。
问题 1:这可能是创建动态数组的另一种方法吗?
问题2:代码是否正确?
问题3:如果[]只能包含const,为什么代码有效?
gcc扩展名. 这在 C 中已经允许很长时间了,但直到 C++14 才使其成为 C++ 标准。gcc通过提供 a-std=c++98或-std=c++11编译器标志来表明您不想使用扩展。如果您需要在 C++ 中使用动态大小的数组,更好的方法是使用std::vector<T>. 它为您提供动态分配数组的灵活性,并为您管理分配的内存。
| 归档时间: |
|
| 查看次数: |
5056 次 |
| 最近记录: |