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

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

问题描述

这是一个很长一段时间,因为我与基本阵列的基本编译器已经设定,但最近我看到一个数组声明是这样的:

  INTÿ;
CIN>> Y;
诠释Z [Y];

用来给误差

旧时光编译器数组的存储大小不是恒定的。后来我发现了在C99可变大小的数组。我不知道他们内部是如何工作的。这是否使得阵列的动态?这是在内存堆中分配?这是否绑定还是静态地做了什么?如果是这样如何。


解决方案

  

这是否使得阵列的动态?


这取决于你如何定义动态。 VLA肯定不能放大或缩小,或者,换句话说,它一旦建立改变它的大小。它是动态的,但是,在某种意义上说,它的长度不在编译时已知的。


  

这是内存堆中分配的?


内存分配方式VLA是特定的实现。一般来说,对于VLA存储器是从空间中的呼叫者的堆栈帧进行分配。然后它会自动释放时,其中VLA定义返回到它的调用者,或者如果VLA超出范围,功能

VLA是 的alloca的近亲( ) 功能,pretty多,可以认为具有同样的效果,至少在C假设编译器实现的VLA以同样的方式的alloca ()实现,你可以认为这两个数组作为在技术上在C相同的:

 为int * A =的alloca(的sizeof(int)的* N);
INT B〔N];

该VLA了,但更加紧凑,方便的语法。但最重要的是,VLA由性质具有自动存储持续时间并给出了编译更多的自由来决定是否要摧毁/释放在离开它被声明的范围的阵列,或在从函数返回。

这成为语言如C ++编译器在哪里实现非常重要 RAII成语并必须保证在退出其范围与破坏自动存储持续时间的对象。

请注意,然而,VLA不是当前的C ++语言的一部分,并且是由编译器实现为非标准扩展。 但他们预计在C ++ 14

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];

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?

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?

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.

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];

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.

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.

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天全站免登陆