允许在没有动态分配的情况下运行时的数组大小? [英] Array size at run time without dynamic allocation is allowed?

查看:46
本文介绍了允许在没有动态分配的情况下运行时的数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 C++ 几年了,今天我看到了一些代码,但这怎么可能是完全合法的?

I've been using C++ for a few years, and today I saw some code, but how can this be perfectly legal?

int main(int argc, char **argv)
{
    size_t size;
    cin >> size;
    int array[size];
    for(size_t i = 0; i < size; i++)
    {
        array[i] = i;
        cout << i << endl;
    }

    return 0;
}

在GCC下编译.

如何在没有newmalloc的情况下在运行时确定大小?

How can the size be determined at run-time without new or malloc?

只是为了仔细检查,我在谷歌上搜索了一些和我的所有类似代码都声称会给出存储大小错误.

Just to double check, I've googled some and all similar codes to mine are claimed to give storage size error.

即使是 Deitel 的 C++ 如何编程 p.常见编程错误 4.5 下的 261 个状态:

Even Deitel's C++ How To Program p. 261 states under Common Programming Error 4.5:

只能使用常量来声明自动和静态数组的大小.

Only constants can be used to declare the size of automatic and static arrays.

启发我.

推荐答案

这在 C99 中有效.

This is valid in C99.

C99 标准支持堆栈上的可变大小数组.可能您的编译器也选择支持这种结构.

C99 standard supports variable sized arrays on the stack. Probably your compiler has chosen to support this construct too.

请注意,这与 mallocnew 不同.gcc 分配堆栈上的数组,就像它在 int array[100] 中所做的一样,只需调整堆栈指针即可.没有进行堆分配.这很像 _alloca.

Note that this is different from malloc and new. gcc allocates the array on the stack, just like it does with int array[100] by just adjusting the stack pointer. No heap allocation is done. It's pretty much like _alloca.

这篇关于允许在没有动态分配的情况下运行时的数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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