dynamic array allocation

Greetings C++ gurus,

Here is a question for you guys. I used to think that C++ compiler should not accept dynamic array allocation when the dimension of an array is calculated during run-time, like this:

...
//..compute value of n at run-time
double a[n];
...

However I have a code (below) doing this, and it compiles (in g++ (GCC) 4.7.2 20120920 (Cray Inc.)) and runs just fine. Is it supposed to work like this?

Thanks for any insights,

-Maxim-




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;


int main(void)
{
  int n;

  for (n=2;n<5;n++)
    {

      cout << "array size:" << n << "\n";

      int arr[n]; // run-time allocation???

      for (int i=0;i<n;i++)
	{
	  cout << "arr[" << i << "]=" << arr[i] << "\n";
	}
      cout << "------------------" << "\n";

    }


  return 0;
}

Last edited on
Lots of C++ compilers use a C backend so they will let you do this. There might be some command line args you can pass to prevent this, but I don't know what they would be.
Thanks guys, these compiler flags solve the problem, now it behaves as expected - reports an error if the arrays size is calculated at run-time.
Topic archived. No new replies allowed.