堆栈上的可变大小数组

2022-01-22 00:00:00 arrays stack c++

据我了解,在 C 和 C++ 中,我们在堆栈上创建其大小在编译时已知的数据结构,并且我们将堆(无 malloc/new-delete)用于大小未知的东西编译时间并在运行时决定.那么,我的 g++ 编译器是否允许我执行类似以下代码片段的操作.

It is my understanding that in C and C++ , we create data-structures whose size is known at compile time on the stack and we use the heap (malloc-free / new-delete) for things whose size is not known at compile time and is decided at run-time.Why then , does my g++ compiler allow me to do something like the following code snippet.

int main(void)
{
    int n ;
    cin >> n ; // get the size of array.
    int arr[n] ; // create a variable sized array.
    .... do other stuff ...
}

具体来说,在数组的情况下:
数组在栈上被分配了一块连续的内存,栈上和栈下都有变量,所以必须知道数组的大小,以便栈上数组上面的变量、数组本身和下面的变量堆栈上的数组都可以整齐地放入内存中.堆栈上的可变大小数组是如何实现的? 为什么它们甚至是必要的?为什么我们不能只将堆用于可变大小的缓冲区?

Specifically , in the case of an array:
An array is assigned a contiguous block of memory on the stack and there are variables above and below it on the stack , so the array's size must be known so that the variable above the array on the stack , the array itself , and the variables below the array on the stack can all fit into memory neatly. How then are variable sized arrays on the stack implemented ? Why are they even necessary? Why can't we just use the heap for variable sized buffers?


我从评论中了解到,C 和 C++ 对 VLA 是否标准有不同的规则,还有 Neil Butterworth 的评论,即一次询问两种语言的问题通常不是一个好主意.谢谢大家,所以我从我的问题中删除了 C 标记,因为我打算主要询问 C++,正如代码片段语法所证明的那样.很抱歉造成混乱,并感谢您的回复.


I understand from the comments , that C and C++ have different rules regarding whether VLA's are standard or not and also Neil Butterworth's comment that it is generally not a good idea to ask a question about two languages at once. Thank you people , so I am removing the C tag from my question , as I intended to mainly ask about C++ , as evident by the code snippet syntax. Sorry for the confusion , and thanks for the responses.

推荐答案

在标准 C++ 中不允许,但在标准 C 中允许,g++ 在 C++ 中也允许,作为语言扩展.

They aren't allowed in standard C++, but they are allowed in standard C, and g++ allows them in C++ as well, as a language extension.

那么堆栈上的可变大小数组是如何实现的呢?

How then are variable sized arrays on the stack implemented?

请参阅这个问题.要点是大小 (n) 被评估并存储在编译器生成的局部变量中,然后分配那么多堆栈空间.没有物理定律说堆栈变量的大小必须在编译时知道 - 只是这样更简单.

See this question. The gist is that the size (n) gets evaluated and stored in a compiler-generated local variable, and then that much stack space is allocated. There's no law of physics that says the size of a stack variable has to be known at compile-time - it's merely simpler that way.

为什么它们甚至是必要的?

Why are they even necessary?

他们不是.在您的帮助下,您可以使用动态分配来做同样的事情.

They aren't. As you aid, you can do the same thing with dynamic allocation.

为什么我们不能只将堆用于可变大小的缓冲区?

Why can't we just use the heap for variable sized buffers?

堆栈分配更高效.

相关文章