本文介绍了如何对待编译器变长数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能看起来像一个初学者的问题,但我感兴趣的方式,一个编译器通常创建可变尺寸的阵列,像下面的程序。

This might seem like a beginner's question, but I am interested in the way that a compiler normally creates arrays of variable-dimensions, like in the following program.

#include<iostream>

int main(){
  int n;
  std::cin>>n;
  int a[n];
}

这是我学到的东西,在C所有的初始化值必须是恒定的,所以编译器知道多少内存减去堆栈指针,以适应数组元素的个数在函数内部保留,正常成立。

From what I've learnt, in C all the initializer values must be constant, so that the compiler knows how much memory to reserve inside the function, normally by subtracting the stack pointer in order to accomodate the number of elements the array holds.

这对我来说很有意义。
不过,我不明白编译器如何对待上面的程序,因为它似乎与G ++(MinGW的)工作,但失败,氯,微软的C ++编译器。我怀疑,海湾合作委员会分配的堆内存槽非标准扩展,但我不知道这一点。

This makes sense to me.However, I don't quite understand how compilers treat the above program, since it seems to work with G++(MinGW) , but fails with Cl, Microsoft's C++ compiler. I suspect that GCC allocates memory on the heap trough a non-standard extension, but I am not sure of this.

此外,微软的编译器是不是有名的是符合标准的,所以我也不会感到惊讶,如果它实际上可能是错在它把上述程序的方式。

Also, Microsoft's compiler is not renowned for being standards-compliant, so I wouldn't be surprised if it may actually be wrong in the way it treats the above program.

推荐答案

在C标准的C99版,可变长度数组是允许的。然而,它们不是在C ++的任何版本的允许;你看到一个G ++的扩展。需要注意的是微软的C编译器不完全支持C99;因为G ++支持C99它很容易应用到C ++的支持VLA作为扩展。

In the C99 version of the C standard, variable length arrays are permitted. However, they are not permitted in any version of C++; you're seeing a G++ extension. Note that Microsoft's C compiler does not fully support C99; since G++ supports C99 it's easy enough to apply the VLA support to C++ as an extension.

至于如何编译器通常实现沃拉斯,这是一样的的alloca()(除了它具有围绕保持一定的尺寸为的sizeof ) - 编译器保存原始堆栈指针,再由然而,许多字节调整下来,它计算它需要。不足之处是函数入口和出口是一个比较复杂一点,因为编译器需要存储在哪里堆栈指针复位到,而不是仅仅通过固定的常数调整。

As to how the compiler usually implements VLAs, it's the same as alloca() (except that it has to keep the size around for sizeof) - the compiler saves the original stack pointer, then adjusts it down by however many bytes it calculates that it needs. The downside is function entry and exit is a bit more complicated as the compiler needs to store where to reset the stack pointer to rather than just adjusting by fixed constants.

这篇关于如何对待编译器变长数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:28