1

Possible Duplicate:
why a[n] is accepted in c during runtime?
Declaring the array size with a non-constant variable

I just wrote some code to test some other code and I needed an array as input data. As the size of the input data may differ, I declared the variable as follows:

float input[num_pixels_row][num_pixels_col][3];

where num_pixels_row and num_pixels_col are non-const variables which are set using input from the command line. I ran the code and it worked.

Then after a little while I noticed what I had just done and thought "Hey, wait a minute! This shouldn't work!!" But the strange thing is that it does. Since input is declared inside a function it should be allocated on the stack, but how can the compiler determine the stack frame if the size of the array isn't known?

I asked two colleagues and they were just as puzzled. By the way, I compiled the code using g++ 4.6.1

Community
  • 1
  • 1
gablin
  • 4,678
  • 6
  • 33
  • 47

2 Answers2

4

That's a gcc-specific compiler extension which makes your code sub-standard and nonportable. For example, this won't compile in Visual C++.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
3

Variable length arrays are a part of the C99 specification, which gcc also allows in C++ programs.

I don't think this has been added to C++11 though, unfortunately. Though I'd suspect that since many C++ compilers also strive for C compliance that they'll end up supporting this as well.

edA-qa mort-ora-y
  • 30,295
  • 39
  • 137
  • 267