编译器如何解决变量的变长数组后声明的地址? [英] How does the compiler resolve the address of variable declared after a variable-length array?

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

问题描述

假设我有以下的功能,它利用一个可变长度的数组:

Suppose I have the following function, which makes use of a variable-length array:

void func(int size)
{
    int var1;
    int arr[size];
    int var2;
    ...
}

编译器如何确定 VAR2

这是我可以把想到的是唯一的办法改编 VAR1 VAR2

The only way that I can think of is by placing arr after var1 and var2.

但在这种情况下,如果有什么有几个变长数组?

But in that case, what if there were several variable-length arrays?

配售所有的正常变量后,只会有助于解决第一个地址。

Placing all of them after the "normal" variables would only help resolving the address of the first one.

我这里隐含的假设是,所有的局部变量(包括沃拉斯)在栈上分配的。

My implicit assumption here is that all the local variables (including VLAs) are allocated on the stack.

我意识到,这不是由C99标准定义的,所以这个问题是在大约编译本质。

I realize that it is not defined by the C99 standard, so the question is in essence about compilation.

推荐答案

下面是一个可能的模式。 改编看作一个(固定大小)指针堆栈分配数组:

Here is one possible model. Think of arr as a (fixed-size) pointer to a stack-allocated array:

int var1;
int *arr = alloca(sizeof(int) * size);
int var2;

请注意如何三个变量的(相对)位置不与尺寸更改。这种模式很容易推广到多个沃拉斯。

Note how the (relative) location of the three variables does not change with size. This model readily generalizes to multiple VLAs.

请注意,这仅仅是一个例子。每个编译器自由地实现沃拉斯但它为所欲为。如果你想知道的的编译程序,看看生成的程序集code。

Note that this is only an example. Each compiler is free to implement VLAs however it pleases. If you want to know what your compiler does, look at the generated assembly code.

这篇关于编译器如何解决变量的变长数组后声明的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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