Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how am i able to declare an array with variable length determined at runtime in 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];

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...

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;
}

Please shed some light..

Thanks.

like image 752
ashishsony Avatar asked Jan 20 '26 04:01

ashishsony


2 Answers

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

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:

  • data on the stack is automatically cleaned up when it goes out of scope
  • only something like 1MB is typically allocated for the stack. Large datastructures should go on the heap instead.

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++)

like image 192
jalf Avatar answered Jan 22 '26 17:01

jalf


You have to allocate it on the heap, using new :

int* ch = new int[ a ];

but don't forget to deallocate it after usage :

delete [] ch;

A better way would be to use a std::vector that does exactly what you want.

like image 36
Klaim Avatar answered Jan 22 '26 18:01

Klaim