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

标签 c++ arrays

我是 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,为什么代码可以工作?

最佳答案

  1. 正确,您发现了a gcc extension .这在 C 中已经允许了很长时间,但直到 C++14 才将其纳入 C++ 标准。
  2. 是的,代码是正确的,前提是您可以使用该语言的不可移植扩展。
  3. 符合标准的编译器也是如此。你可以告诉gcc您不想通过提供 -std=c++98 使用扩展或 -std=c++11编译器标志。

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

关于c++ - 没有 new 的动态数组 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25474248/

相关文章:

javascript - 在 JavaScript 中检查嵌套数组是否包含另一个嵌套数组的任何元素

java - 如何使用数组列表解析 json 响应

php - PHP数组索引的问题

arrays - 将值推送到数组nodejs

c++ - 尝试创建线程的问题

c++ - 绕道钩住 CreateFile 函数触发堆栈溢出

C++ 双指针转换

c++ - 变体实现(可变参数模板)C++

c++ - 32 位、64 位和 80 位浮点 IEEE-754 的可表示值范围?

ios - 使用 AlamofireObjectMapper 将对象 json 数据映射到 2 个单独的数组中