简体   繁体   English

由变量给出的C数组大小

[英]C array size given by variable

I found some code today that confused me. 我今天发现一些代码让我困惑。 It did something like this: 它做了这样的事情:

#include <stdio.h>

int main(int argc, char **argv) {
    int x = 5;
    int foo[x];

    foo[0] = 33;
    printf("%d\n", foo[0]);
    return 0;
}

My Question is why does this work? 我的问题是为什么这有效?

The array foo is on the stack so how could it be expanded by x ? 数组foo在堆栈上,那怎么可以用x扩展呢?

I would have expected some thing like this: 我本以期待这样的事情:

#include <stdio.h>

int main(int argc, char **argv) {
    int x = 5;
    int foo[] = malloc(sizeof(int)*x);

    foo[0] = 33;
    printf("%d\n", foo[0]);
    free(foo);
    return 0;
}

Not that it is prettier or something but, I just wonder. 并不是说它更漂亮或者其他东西,但我只是想知道。

The snippet 片段

int foo[x];

is talking advantage of something called VLA ( Variable length array ) feature. 正在谈论称为VLA( 可变长度阵列 )功能的东西。 It was introduced in C99 standard, just to be made an optional feature in C11 . 它是在C99标准中引入的,只是在C11作为可选功能。

This way, we can create an array data structure, whose length is given (supplied) at run-time. 这样,我们就可以创建一个数组数据结构,其长度在运行时给定(提供)。

Point to note, though created at runtime, gcc allocates the VLAs on stack memory (unlike the dynamic memory allocation from heap memory). 值得注意的是,虽然在运行时创建,但gcc会在堆栈内存上分配VLA(与堆内存中的动态内存分配不同)。

The array foo is on the stack so how could it be expanded by x? 数组foo在堆栈上,那怎么可以用x扩展呢?

gcc simply moves the stack pointer: gcc只是移动堆栈指针:

subq    %rax, %rsp

Link to full example with assembly output 链接到装配输出的完整示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM