I had a computer science class at school and our teacher was talking about dynamic memory allocation and why
cin>>size;
int array[size]; // According to him this should result in a compiler error
this shouldn’t work and instead we were supposed to use:
int *p, size;
cin>>size;
p = new int[size]
...
delete[] p;
My question is, why does the first example work if you cannot declare dynamically arrays like that?
UPDATE: All tests are made in GNU GCC Compliler and the code above is inside the main function
You’re using a non-standard compiler, that supports variable length arrays. Your professor is right,
int array[size]shouldn’t compile.Your professor is also
wrongtelling you to usep = new int[size]. What he should do is tell you to usestd::vector<int> p(size). (okay, for educational purposes this is OK) 🙂