c++ - 为什么这不起作用 : `int arr[size]` but this does `int* arr = new int[size]` ?

标签 c++ arrays

我目前正在学习 C++。来自 Java,很多东西对我来说真的很奇怪。

有时我尝试创建一个大小在运行时确定的数组,如下所示:

int size = functionCall(argument);
int array[size];

编译并运行,但在程序的后面给出了非常奇怪的输出。

有人告诉我我必须这样做:

int size = functionCall(argument);
int* array = new int[size];

因为 new 允许动态分配内容,也就是说,如果我理解正确,则根据仅在运行时已知的内容进行分配。

两个问题:

1- 我对 new 的理解是否正确?

2- 为什么 C++ 不允许我的代码的第一个版本?

最佳答案

At some point I tried to create an array of a size that's determined at runtime, like so: This compiled and ran, but gave really weird output later in the program.

您创建的是一个名为 VLA(又名 Variable-length Array)的非标准扩展。它应该有效,真的,但由于它没有,我假设你这边出了问题。

Because new allows stuff to be dynamically allocated, i.e. if I understand correctly allocated according to something that's only known at runtime.

是的,你的直觉是正确的。

1- Is my understanding of new correct?

是的。您使用 new 动态分配内存。但这打开了另一个蠕虫 jar 头。

2- Why doesn't C++ allow the first version of my code?

C++ 标准不支持 VLA。我觉得这样做的原因超出了问题的范围。

无论哪种情况,如果您想要一个基于 C++ 中运行时变量的动态数组,我们倾向于使用 std::vector .你的代码最终会变成这样:

std::size_t size = get_size();
std::vector<int> arr(size);

现在您可以像使用常规 C 数组一样使用 std::vector。使用 std::vector 而不是 raw new 的好处在于,它减轻了您使用 delete[] 的负担,并且在之前遇到异常时还提供了强大的异常安全性你到达调用 delete[] 的行。

关于c++ - 为什么这不起作用 : `int arr[size]` but this does `int* arr = new int[size]` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26162586/

相关文章:

c++ - 使用 gcc 调用纯虚函数时出现链接器错误

c++ - 表达式必须是可修改的指向字符的左值指针参数

c++ - Qt 数据类型选择

c - 很长的整数列表的数组

javascript - 使用嵌套对象

ios - 异步创建包含图像的数组

c++ - 动态链接

c++ - 在构造一个定义了某个大类型的基类成员的派生类时,我应该如何传递值?

c - 将数组值重置为 0 的最简单方法是什么?

arrays - 如何在 Swift 中从字符串数组中过滤对象