-1

I was trying to make a dynamic array in this form :

int x;
cin>>x;
int ar[x];

My g++ (gcc) compiler on Linux refused to create an array without a fixed size. However using the same code on windows on dev-cpp, it was complied and executed, also it allows me to create and use the dynamic array, i thought it was a compiler bug, however when i restarted and returned to g++ it compiled and executed the code although it refused to do it before I tried the code on windows, how can that be and is it dangerous?

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
essam tarik
  • 25
  • 2
  • 8
  • 1
    you didnt do what you said you did. G++ is perfectly happy with dynamically size arrays like you have. Post the exact code that got the error and what the error said – pm100 Mar 04 '14 at 16:51

2 Answers2

1

C++ requires the size of an automatic storage array to be known at compile time, otherwise the array must be dynamically allocated (unless with compiler extension).

You should use

int *ar = new int[x];
...
delete []ar; // free the memory after use

or

vector<int> ar;
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
0

As the other answerers point out, if you don't know the size of the array at compile time then you should dynamically allocate using new. But (somehwat shamefully) they fail to tell you that you will be responsible for deallocating this memory with delete : details here

This responsibility (making sure you always release memory you have allocated) is the biggest source of problems in C++. A technique like RAII can make this easier (put simply : wrap the memory in an object, new in the constructor and delete in the destructor, then the language makes sure the destructor is always called)

Community
  • 1
  • 1
Graham Griffiths
  • 2,196
  • 1
  • 12
  • 15
  • i need to make something clear , i actually know that the way of : int x;cin>>x;int ar[x]; is actually a wrong way to do it , the problem here is that some magic happened , my GCC refused to compile this code due to an unfixed size of the array , later on after i restarted my machine GCC now compiles this very same code with no errors , thats what i wanted to know , how can it compile the same code it refused to compile before the restart ???!!!!!! – essam tarik Mar 05 '14 at 08:17
  • it is defintely the same version of GCC before and after? with the same command line? – Graham Griffiths Mar 05 '14 at 09:20
  • yes it is , the same GCC version , the same machine and the same linux distro , i just restarted nothing more , thats why i said "magic" !!! – essam tarik Mar 05 '14 at 13:45