我如何在C ++中声明一个在运行时确定的具有可变长度的数组? [英] how am i able to declare an array with variable length determined at runtime in C++?

查看:200
本文介绍了我如何在C ++中声明一个在运行时确定的具有可变长度的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请检查此代码,使其编译并运行完全正常. 问题是,当我开始学习c ++(turbo c ++)时,我再也无法将任何类型的数组声明为..

Please check this code out it compiles and runs absolutely fine.. The question is that when i started learning c++ (turbo c++) i never was able to declare an array of any type as ..

datatype var[variable_set_at_runtime];

我认为这在最新的gcc编译器中是不可能的...但是令人惊讶的是,这是可能的...

and i took it for granted that this cant be possible in latest gcc compilers...but surprisingly this is possible...

所以我的相关问题是,那么新操作员又需要什么?

So my related question is that whats the need of new operator then??

我知道新操作员会做很多事情,包括在运行时在堆中动态分配内存,将地址返回给该资源等.

I know that new operator does a lot of things including dynamically allocating memory at runtime in heap,returning an address to that resource...etc..

我感觉到什么是我的代码动态地在堆栈上分配内存,而新的则在堆上分配内存呢?这是唯一的区别...

What difference i feel is that my code dynamically allocates the memory on stack while new does it on heap?? is this the only difference...

我写完这样的东西后真的很惊讶,因为当我开始学习c ++时我做不到……添加到它上,我也可以为自定义数据类型做这件事...:-O

i am really astonished after writing something like this as i could not do this when i started learning c++ and ...to add to it i can do this for custom data types too... :-O

#include<iostream>
using namespace std;
struct A
{
    int a;
    int b;
};
int main()
{
    int a;
    cin>>a;
    int ch[a];
    for(int i=0;i<a;i++)
        ch[i]=i+1;
    for(int i=0;i<a;i++)
        cout<<"\n\nch=="<<ch[i];
    A obj[a];
    cin>>obj[a-1].a;
    cin>>obj[a-1].b;
    cout<<"\n\n obj.a,obj.b=="<<obj[a-1].a<<" , "<<obj[a-1].b;
}

请说明一下.

谢谢.

推荐答案

我认为这是理所当然的 在最新的gcc中不可能 编译器...但是令人惊讶的是 可能...

and i took it for granted that this cant be possible in latest gcc compilers...but surprisingly this is possible...

这在C语言中合法,但在C ++中不合法. GCC可能会根据编译器标志允许它,但是如果您按照严格的C ++编译代码(应该这样做),则不允许使用动态长度数组,并且必须使用new. (我很惊讶,没有人提到这个小细节)

It is legal in C, but not C++. GCC might allow it depending on compiler flags, but if you compile your code as strict C++ (which you should), dynamic-length arrays are not allowed, and you have to use new. (I'm surprised no one has mentioned this little detail yet)

除此之外,其他两个大区别是:

Apart from this, the two other big differences are that:

  • 堆栈中的数据超出范围会自动清除
  • 通常只为堆栈分配1MB之类的内容.大型数据结构应该放在堆上.

但是,实际上,最重要的一点是第一个-它不是有效的C ++. (而且正如Neil指出的那样,它在C ++ 0x中也无效.没有计划将其添加到C ++中)

But really, the single most important point is the first one -- it's not valid C++. (And as Neil pointed out, it is not valid in C++0x either. There are no plans of adding this to C++)

这篇关于我如何在C ++中声明一个在运行时确定的具有可变长度的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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