可变长度数组 VLA(静态绑定或动态) [英] variable length arrays VLA (static binding or dynamic)

查看:26
本文介绍了可变长度数组 VLA(静态绑定或动态)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经很久没有使用基本数组在基本编译器中进行编程了,但最近我看到了这样的数组声明:

It has been a long time since I have programmed in basic compilers with basic arrays, but recently I saw an array declaration like this:

int y;
cin>>y;
int z[y];

旧时编译器用于给出错误数组的存储大小不是恒定的".然后我发现了 C99 中的可变大小数组.我想知道他们是如何在内部工作的.这会使数组动态吗?这个内存是在堆上分配的吗?这个绑定是否仍然是静态完成的?如果是,如何.

old time compilers used to give error "Storage size of array isn't constant". Then I found out about variable size arrays in C99. I wonder how they work internally. Does that makes array dynamic? Is this memory allocated at heap? Does this binding is still done statically? If so how.

推荐答案

这会使数组动态化吗?

Does that makes array dynamic?

这取决于您如何定义动态".VLA 肯定不能增长或缩小,换句话说,一旦创建就不能改变其大小.但是,从某种意义上说,它是动态的,它的长度在编译时是未知的.

It depends how you define "dynamic". VLA certainly cannot grow or shrink or, in other words, change its size once it is created. It is dynamic, though, in a sense that its length is not known in compile-time.

这个内存是在堆上分配的吗?

Is this memory allocated at heap?

如何为 VLA 分配内存是特定于实现的.一般来说,VLA 的内存是从调用者堆栈帧中的空间分配的.当定义了 VLA 的函数返回到它的调用者时,或者如果 VLA 超出范围,它就会自动释放.

How the memory is allocated for the VLA is implementation specific. Generally speaking, the memory for the VLA is allocated from space in the stack frame of the caller. It is then automatically freed when the function where VLA is defined returns to its caller, or if VLA goes out of scope.

VLA 的近亲是 alloca() 函数,这几乎可以被认为具有相同的效果,至少在 C 中是这样.假设编译器以与 alloca() 的实现方式相同的方式实现 VLA,您可以认为这两个数组在 C 中在技术上是相同的:

The closest relative of VLA is alloca() function, which pretty much can be considered to have the same effect, at least in C. Assuming that compiler implements the VLA the same way alloca() is implemented, you can think of these two arrays as being technically the same in C:

int *a = alloca(sizeof(int) * N);
int b[N];

然而,VLA 具有更紧凑和方便的语法.但最重要的是,VLA 本质上具有自动存储持续时间,并让编译器更自由地决定是在离开数组声明的范围还是从函数返回时销毁/释放数组.

The VLA has, however, more compact and convenient syntax. But most importantly, VLA by nature has an automatic storage duration and gives compiler more freedom to decide whether to destroy/free the array upon leaving the scope where it was declared, or upon returning from the function.

这在 C++ 等语言中变得非常重要,其中编译器实现了 RAII idiom 并且必须保证在退出范围时销毁具有自动存储持续时间的对象.

This becomes very important in languages such as C++ where compiler implements RAII idiom and must guarantee to destroy objects with automatic storage duration upon exiting their scope.

但是请注意,VLA 目前不是 C++ 语言的一部分,而是由编译器作为非标准扩展实现的.但它们有望成为 C++14 的标准.

Note, however, that VLA is not currently a part of C++ language and is implemented by compiler as a non-standard extension. But they are expected to become standard in C++14.

这篇关于可变长度数组 VLA(静态绑定或动态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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