当我在 this tutorial 中阅读有关数组初始化的内容时.我发现了这张纸条。
type name [elements];
NOTE: The elements field within square brackets
[]
, representing the number of elements in the array, must be a constant expression, since arrays are blocks of static memory whose size must be determined at compile time, before the program runs.*
据我所知,数组在运行时分配内存。这应该是假的吧?或者它是什么意思?
最佳答案
请检查以下答案是否有助于让您清楚地了解这一点。
Static array vs. dynamic array in C++
静态数组是在堆栈上创建的,并且必须具有固定大小(在进入函数时需要知道堆栈的大小): int foo[10];
动态数组是在堆上创建的。它们可以有任何大小,但你需要自己分配和释放它们,因为它们不是堆栈框架的一部分: int* foo = new int[10]; 删除[] foo;
你不需要处理静态数组的内存管理,但是当它们所在的函数结束时它们会被销毁
Array size at run time without dynamic allocation is allowed?
C99 标准 ( http://en.wikipedia.org/wiki/C99 ) 支持堆栈上可变大小的数组。一些编译器可能会实现这些标准并支持可变大小的数组。
关于c++ - 数组的大小是在编译时确定的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26175859/