c++ - 什么时候使用动态数组而不是静态数组合适?

标签 c++ arrays memory-management dynamic

动态和静态数组:当两者都可能时,通常使用一个而不是另一个的基本原理是什么?


其中一种情况可能是

int n;
cin >> n;
int a[n];

对比

int n;
cin >> n;
int* a = new int[n];

最佳答案

int a[n] 是一个可变长度数组,这是 C++ 标准不允许的,因此您应该选择第二个代码片段。

使用 -pedantic 标志,你应该得到:

warning: ISO C++ forbids variable length array 'a' [-Wvla]
     int a[n];
            ^

关于c++ - 什么时候使用动态数组而不是静态数组合适?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46877631/

相关文章:

JavaScript 数组转换

c - 释放指向指针结构的指针

c++ - 将 const unique_ptr 引用作为参数传递

c++ - 调用 "SetDllDirectory"时表达式: string iterators incompatiable,

javascript - 使用 javascript 数组填充 JSON 并修改条目

memory-management - 没有实现Copy的结构在哪里分配,如何从函数中返回它?

c - 无效指针错误

c++ - 如何从 C++ 程序执行命令行命令

c++ - 错误 Id 到错误字符串映射 - C++ 中的实现

C : text file, 字符串比较等