Number of elements in array - needs to be constant?

Hi all,

I'm reading the C++ language tutorial, and I noticed that the author insists on the idea that the difference between arrays and dynamic memory is that the number of elements of an array has to be a constant so that the size of the array is known at compilation:

The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed


You could be wondering the difference between declaring a normal array and assigning dynamic memory to a pointer, as we have just done. The most important difference is that the size of an array has to be a constant value, which limits its size to what we decide at the moment of designing the program, before its execution, whereas the dynamic memory allocation allows us to assign memory during the execution of the program (runtime) using any variable or constant value as its size.


And then a small program is given as an example to illustrate this... but if I adapt this program to use an array instead of a block of memory, it compiles and runs just fine!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

int main ()
{
  int i,n;
  cout << "How many numbers would you like to type? ";
  cin >> i;
  int p[i];

  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] << ", ";

  return 0;
}


My compiler isn't bothered that it doesn't know the size of the array until runtime... So does it depend on what compiler we use?

Thanks in advance
So does it depend on what compiler we use?

Yes, GCC supports this as an extension. It doesn't matter though - it's not valid C++, so you shouldn't use it. There are vectors for that.
OK... thanks!
if you're using gcc, use the commandline argument -pedantic or, to warn about just this one non-standard language extension, -Wvla
Last edited on
Topic archived. No new replies allowed.