Code:Blocks Mingw Compiler Error: Variable-Sized O

2019-07-19 15:19发布

问题:

I am creating a simple terminal fantasy game using C++. I have seemed to run into an error "error: variable-sized object 'items' may not be initialized". Here is the code:

string useItem(int item)
{
    string items[item] = {"HP Potion","Attack Potion","Defense Potion","Revive","Paralize Cure"};
}

I want to be able to use this function in order to access and return an item. How can I fix this error. I am using Code::Blocks with mingw compiler.

回答1:

There are a couple of issues here, one variable length arrays is a C99 feature and is not part of the ISO C++ but several compilers support this feature as an extension including gcc.

Secondly C99 says that variable length arrays can not have an initializer, from the draft C99 standard section 6.7.8 Initialization:

The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.

and alternative is to use:

string items[] = { ... } ;

and array of unknown size will have its size determined by the number of elements in the initializer.

Alternatively the idiomatic C++ way to have array of variable size would be to use std::vector.