由变量给出的 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;
}
我的问题是为什么这行得通?
数组foo
在栈上,如何用x
展开?
The array foo
is on the stack so how could it be expanded by 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;
}
并不是说它更漂亮什么的,但是,我只是想知道.
Not that it is prettier or something but, I just wonder.
推荐答案
代码段
int foo[x];
正在谈论称为 VLA(可变长度数组)功能的优势.它是在 C99
标准中引入的,只是为了在 C11
中成为一个可选特性.
is talking advantage of something called VLA (Variable length array) feature. It was introduced in C99
standard, just to be made an optional feature in C11
.
通过这种方式,我们可以创建一个数组数据结构,其长度在运行时给出(提供).
This way, we can create an array data structure, whose length is given (supplied) at run-time.
需要注意的是,尽管在运行时创建,gcc
在堆栈内存上分配 VLA(与从堆内存中动态内存分配不同).
Point to note, though created at runtime, gcc
allocates the VLAs on stack memory (unlike the dynamic memory allocation from heap memory).
这篇关于由变量给出的 C 数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!