没有 new 的动态数组 (C++)

Sur*_*raj 6 c++ arrays

我是 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,为什么代码有效?

das*_*ght 6

  1. 正确,您发现了一个gcc扩展名. 这在 C 中已经允许很长时间了,但直到 C++14 才使其成为 C++ 标准。
  2. 是的,代码是正确的,假设您可以使用该语言的不可移植扩展。
  3. 这对于符合标准的编译器来说是正确的。您可以gcc通过提供 a-std=c++98-std=c++11编译器标志来表明您不想使用扩展。

如果您需要在 C++ 中使用动态大小的数组,更好的方法是使用std::vector<T>. 它为您提供动态分配数组的灵活性,并为您管理分配的内存。

  • 它也不在 C++14 中。我相信他们现在正在等待可接受的库包装器,因为 `std::dynarray` 失败了。 (2认同)