Code:Blocks Mingw Compiler Error: Variable-Sized Object May Not Be Initialized

我只是一个虾纸丫 提交于 2019-12-23 21:14:01

问题


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.



来源:https://stackoverflow.com/questions/27339014/codeblocks-mingw-compiler-error-variable-sized-object-may-not-be-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!