可变定的C数组的大小 [英] C array size given by variable

查看:96
本文介绍了可变定的C数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些code今天我弄糊涂了。
它确实是这样的:

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;
}

我的问题是,为什么这会起作用?

阵列是堆栈所以怎么可能通过扩大在X

The array foo is on the stack so how could it be expanded by 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;
}

不在于它是prettier什么的,但我不知道。

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 分配沃拉斯的堆栈存储器(不像从堆内存的动态内存分配)。

Point to note, though created at runtime, gcc allocates the VLAs on stack memory (unlike the dynamic memory allocation from heap memory).

这篇关于可变定的C数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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