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.
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.8Initialization:and alternative is to use:
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.