How to declare a variable length array in Visual S

2020-04-07 19:56发布

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条回答
欢心
2楼-- · 2020-04-07 19:56

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.

查看更多
叛逆
3楼-- · 2020-04-07 20:22

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

查看更多
登录 后发表回答