如果我只能创建一个数组,为什么还需要动态内存分配?

Why do I need dynamic memory allocation if I can just create an array?

我正在阅读有关动态内存分配和静态内存分配的内容,发现以下有关动态内存分配的内容:

In the programs seen in previous chapters, all memory needs were determined before program execution by defining the variables needed. But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input.

所以我用C++写了下面的程序:

#include <iostream>

int main()
{
  int n = 0;
  int i = 0;

  std::cout << "Enter size: ";
  std::cin >> n;
  int vector[n];

  for (i=0; i<n; i++)
  {
    vector[i] = i;
  }

  return 0;
}

这个程序有效。 我不明白它是如何工作的。 这里的大小是什么时候确定的? 在这种情况下如何分配向量?

根据this(强调我的):

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.

请注意,这只是一个扩展,并不适用于所有编译器,例如它不适用于我的 MSVC(我收到错误 "expression must have a constant value")。

以上代码将在最新版本的 compiler.This 中生成错误代码将在旧版本的 DOSBOX 中运行。

数组的大小必须是常量整数。

所以你可以用两种方式定义它

1.#define Macron

#include<iostream>
#define n 5

main() {
   ...
      ...
      int array[n];
}

2.const 关键词

#include<iostream>
....
main() {
   int x;
   cout << "Enter Size Of Array";
   cin >> x;

   const int n = x;

   int array[n];
   ...
      ...
}