adk
adk

Reputation: 4599

Variable Sized Arrays in C

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

Upvotes: 7

Views: 754

Answers (5)

sigjuice
sigjuice

Reputation: 29759

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.

Upvotes: 4

Mandrake
Mandrake

Reputation: 361

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

Upvotes: 0

Jim Buck
Jim Buck

Reputation: 20726

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);

Upvotes: 3

rpetrich
rpetrich

Reputation: 32316

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

Upvotes: 9

rlbond
rlbond

Reputation: 67759

It is in C99. MSVC only supports C89.

Upvotes: 13

Related Questions