2

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.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Shawn S.
  • 107
  • 9
  • Raw arrays size must be known at compiled time. Otherwise you should use std::vector – Borgleader Dec 07 '14 at 02:46
  • `char const* items[] = ...`? – Michael Burr Dec 07 '14 at 02:47
  • It is also helpful to note the compiler and version you are using, in this case the answer does not change much but in other questions it could make a big difference. – Shafik Yaghmour Dec 07 '14 at 03:32
  • Aside from the technical issues that Shafik pointed out; this code doesn't seem to make any sense. I think you actually wanted to do `string items[] = { "HP Potion", ` ... `}; return items[item];` , although you should also check `item` is in range of the number of strings in the array – M.M Dec 08 '14 at 03:00

1 Answers1

2

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.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740