tags:

views:

328

answers:

5

I guess my question is whether the following is valid C

int main(void) {
  int r = 3;
  int k[r];
  return 0;
}

If so, would some one care to explain why it does not work in Microsoft's C compiler, but in GCC, and when it was added to the C standard.

Thank you

+11  A: 

It is in C99. MSVC only supports C89.

rlbond
+8  A: 

The C99 standard added variable-length arrays, but other vendors such as GCC added them much earlier.

rpetrich
+2  A: 

It is a GCC extension that the current MSVC does not support. You can replace it in MSVC fairly easily with an _alloca (a stack allocation that requires no manual deallocation on the part of the programmer):

#include <malloc.h>

...

int *k = (int *)_alloca(sizeof(*k)*r);
Jim Buck
It was a GCC extension, but was codified into C99. MSVC indeed does not support it yet. Note also that on Linux, it's alloca(), not _alloca, and is in <alloca.h>
bdonlan
It has been standardized for 10 years...
Matthew Flaschen
I have always used this, but did not get the error until I used windowsthis clears up my confusion
adk
+2  A: 

I'm sorry this is not an answer, but I'd like to point out a potential problem with using variable-length arrays. Most of the code that I have come across looks like this.

void foo(int n)
{
    int bar[n];
    .
    .
}

There is no explicit error checking here. A large n can easily cause problems.

sigjuice
A: 

It is a GCC extension that the current MSVC does not support. You can replace it in MSVC fairly easily with an _alloca (a stack allocation that requires no manual deallocation on the part of the programmer)

yes but it is limited to 1mb

Arabcoder