由变量给出的C数组大小

max*_*t89 4 c arrays

我今天发现一些代码让我困惑.它做了这样的事情:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么这有效?

数组foo在堆栈上,那怎么可以扩展x呢?

我本以期待这样的事情:

#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;
}
Run Code Online (Sandbox Code Playgroud)

并不是说它更漂亮或者其他东西,但我只是想知道.

Sou*_*osh 9

片段

int foo[x];
Run Code Online (Sandbox Code Playgroud)

正在谈论称为VLA(可变长度阵列)功能的东西.它是在C99标准中引入的,只是为了成为一个可选功能C11.

这样,我们就可以创建一个数组数据结构,其长度在运行时给定(提供).

注意,虽然在运行时创建,但是gcc在堆栈内存上分配VLA(与堆内存中的动态内存分配不同).