c++ - 为什么在某些编译器中可以声明一个数组,如 int myarr[noconstant];而不是在其他人身上?

标签 c++ dynamic-memory-allocation

<分区>

我看到在 GCC 和 Clang 中有效的代码如下:

size_t size;
cin >> size;
int arr[size];

工作。但是当然这是不可能的,因为它不是常量表达式。那么,这是为什么呢?如果我们这样做,编译器是否会获取动态内存并自动为我们释放它? (顺便说一句,这在 Visual C++ 中无效)

最佳答案

这就是所谓的 Variable-length array .它不是 C++ 的一部分,但它作为扩展被一些编译器(如 GCC 和 Clang)支持。这就是为什么它在那些编译器上编译得很好,但它不是合法的 C++。在 GCC 上,您可以使用此编译器标志禁用 VLA:

-Werror=vla

根据 GCC documentation :

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. For example:

FILE *
concat_fopen (char *s1, char *s2, char *mode)
{
  char str[strlen (s1) + strlen (s2) + 1];
  strcpy (str, s1);
  strcat (str, s2);
  return fopen (str, mode);
}

关于c++ - 为什么在某些编译器中可以声明一个数组,如 int myarr[noconstant];而不是在其他人身上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59224288/

相关文章:

c - 如何在结构中分配内存使其连续

分配后未更新 C++ 字符串大小

C++ - 发送的请求未到达其他计算机

c - 从 txt 文件读取到动态分配

c++ - C/C++ : Deallocating or deleting a block of dynamically created memory

c++ - 当内存分配数不总是相同时如何检测内存泄漏?

c - 读取缓冲区分配 (C)

C++ |如何在每次不返回值的情况下循环 If 语句

c++ - 使用 CString::Format 格式化长值时的错误 (??)

c++ - 从数组构造 vector