在运行时允许数组大小而不进行动态分配吗? [英] Array size at run time without dynamic allocation is allowed?

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

问题描述

我已经使用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编译。

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

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

只是仔细检查一下,我已经在Google上搜索了一些类似的代码,但都声称它们给出了存储大小错误。

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

甚至Deitel的C ++如何编程常见编程错误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。

C99标准在堆栈上支持可变大小的数组。

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

请注意,这与 malloc new不同 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天全站免登陆