堆栈上大小可变的数组 [英] Variable sized array on the stack

查看:110
本文介绍了堆栈上大小可变的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,在C和C ++中,我们创建数据结构,该数据结构的大小在堆栈上的编译时已知,并且我们使用堆(malloc-free/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?


我从评论中了解到,对于VLA是否为标准语言,C和C ++有不同的规则,而且尼尔·巴特沃思(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?

堆栈分配效率更高.

这篇关于堆栈上大小可变的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆