为什么不能创建大小为n的数组? [英] Why can't I create an array of size n?

查看:152
本文介绍了为什么不能创建大小为n的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么我不能创建大小由全局变量确定的数组?

Possible Duplicate:
Why can't I create an array with size determined by a global variable?

这是常量大小为4的简单数组的定义,该数组存储在堆栈存储器中:

This is definition of simple array with constant size 4, which is stored in stack memory:

int array[4];

现在,如果我想在堆栈中声明动态大小的数组,似乎应该编写以下代码:

Now If I want to declare array of dynamic size in stack it seems that I should write this code:

int n;
cin >> n;
int array[n];

但是据我们所知,C ++不允许这样做,而是可以编写此代码,这将在动态内存(即堆)中创建数组:

But as we know this is not allowed in C++ and instead we can write this one, which will create the array in dynamic memory (i.e. heap):

int n;
cin >> n;
int *array = new int[n];

但这会更慢,并且(因为使用了new运算符),并且在完成数组工作之后需要调用delete []运算符.

But this is more slower and (because of using new operator) and requires to call delete [] operator after we finish our work with array.

所以我的问题在这里:

  • 为什么C ++不允许您在堆栈内存中创建动态长度数组?

推荐答案

int n;
cin >> n;
int array[n];

如果使用g ++,这将起作用. g ++支持将VLA作为扩展.但是ISO C ++要求数组的大小必须为常量表达式,即必须在编译时知道大小.

This will work if use g++. g++ support VLAs as an extension. However ISO C++ mandates size of an array to be a constant expression i.e the size must be known at compile time.

为什么C ++不允许您在堆栈内存中创建动态长度数组?

Why is it that C++ don't allow you to create array of dynamic length in stack memory?

简单的回答因为标准是这样的".甚至即将发布的C ++标准(C ++ 0x)也将不允许使用可变长度数组.

Simple answer "Because the standard says so". Even the upcoming C++ Standard (C++0x) is not going to allow Variable Length Arrays.

顺便说一句,我们在C ++中总是有std::vector.因此,没有理由担心. :)

BTW we always have std::vector in C++. So there's no reason to worry. :)

这篇关于为什么不能创建大小为n的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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