I learnt c++ about 6 years ago and I remember in the section about arrays unless you instantiated them using new then their size was static and could only be set in the source code with literal constants, not at run time.
But I was just playing around with a tutorial at
http://www.cplusplus.com/doc/tutorial/dynamic/
and tried to do it without new, and to my surprise it worked. Am I misunderstanding something?
The original code is at the mentioned URL but it isn’t too hard to see what it was from my modified code below.
I realise with strings, vectors etc… arrays aren’t really needed (probably explains why this issue never occurred to me) but just humour me 🙂
// rememb-o-matic
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
// int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
int p[i];
// p= new (nothrow) int[i];
// if (p == 0)
// cout << "Error: memory could not be allocated";
if (false)
cout << "whut?" << endl;
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
// delete[] p;
}
return 0;
}
The code works because most compilers support Variable Length Arrays(VLA) through compiler extensions.
However, Variable Length arrays are not allowed by the C++ standard, Using such a compiler extension would result in your code being non portable and non standard conformant.
Since you are using gcc, Compile your code with
-pedanticoption and it will tell you it is not standard approved.