C / C ++:在运行时数组大小W / O动态分配是允许的? [英] C/C++: Array size at run time w/o dynamic allocation is allowed?

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

问题描述

我一直使用C ++了几年,今天我不知道这是不是一个单纯的brainfart还是什么,但是这怎么可能完全合法的:

I've been using C++ for a few years, and today I don't know if this is a mere brainfart or what, 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编译。如何能的大小可以不新的或malloc的在运行时确定的?只是为了仔细检查,我GO​​OGLE了一些和所有类似codeS矿山都声称给存储大小错误。即使Deitel公司的C ++如何编程页。在常见编程错误4.5 261状态:只有常量可以用来声明自动和静态数组的大小

Compiled under GCC. 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. 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.

请注意,这是从的malloc 不同。 GCC 分配堆栈上的数组,就像它与 int数组呢[100] 仅通过调整堆栈指针。没有堆分配已经完成。这是pretty很像 _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.

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

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