How to declare a variable length array in Visual Studio C89 following other code

3k views Asked by At

I understand in VS all variables must be declared at the top of a block, but if I want a VLA, ie. if I wanted to do something like this:

int result = runalgorithm(); 

int vla[result];

the code above is invalid, because vla must be declared at the top. What is a good solution for this, other than creating an arbitrarily large array?

2

There are 2 answers

1
Natasha Dutta On

You cannot. VLA is supported in C99 and later standards. (Support is mandatory in C99; it is optional in C11.) C89 does not have the VLA concept or support for it.

You can choose dynamic memory allocation, instead. have a look at malloc() and family for your reference.

Remember, if you want to use dynamic memory (allocation), you have to free() the allocated memory once you're done using it.

0
Michael Burr On

MSVC doesn't support VLAs. Recent versions of MSVC do support declarations mixed with statements in C compiles (I think this started with VS 2013).