C++ 静态数组与动态数组类似

标签 c++ arrays static

似乎记得 C++ 中的静态数组只能从 const 表达式初始化,但如果你写:

#include <iostream>

int main() {
  int n;
  std::cin >> n;
  int a[n];
  std::cout << sizeof(a);

  return 0;
}

该程序成功编译(gcc C++17)并打印 n * sizeof(int)。 但为什么会这样呢?

最佳答案

Variable-length arrays不属于标准的一部分。它们可以作为编译器扩展出现,GCC 就是这种情况。编译时您可能会收到以下警告:

warning: ISO C++ forbids variable length array 'a' [-Wvla]

当应用于数组时,sizeof运算符返回整个数组的大小,即基础类型的大小乘以元素数。引用文献指出,我的重点是:

The size of each VLA instance does not change during its lifetime, but on another pass over the same code, it may be allocated with a different size.

标题为 6.19 Arrays of Variable Length 的 GCC 官方文档状态:

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.

话虽如此,更喜欢 std::vectorstd::array到原始(C 风格)数组。

关于C++ 静态数组与动态数组类似,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47968642/

相关文章:

C++ 相当于 JS .charCodeAt()

c++ - 如何初始化指向输出缓冲区长度的指针?

JavaScript:无法操作由 string.match 生成的数组

c++ - 编译错误 : Undefined symbols: "_main", 引用自 : start in crt1. 10.5.o

c++ - 从 SURF 描述符转换为关键点

javascript - 如何删除对象数组中的对象: jquery?

java - 如何解析 CSV(逗号分隔文件)并显示输出

c++ - C 全局静态 - 在线程之间共享?

c++ - C++中静态对象的析构顺序

c++ - 默认情况下全局变量是extern还是相当于在全局中用extern声明变量?