【发布时间】:2017-11-13 21:08:04
【问题描述】:
使用数组处理一些代码,但是我不断收到错误“可变大小的对象可能未初始化”数组中的变量,即使我在之前的行中将它们初始化为 0。这是我的一段代码错误所在。
int main(){
int x = 0;
int y = 0;
int items[x][y] = {}; //Here is where I get the error
for(string food; cin >> food; x++)
{
items[x] = food;
if(food == "done")
cout << "Thank you for inputting.\n";
}
for(double price; cin >>price; y++)
{
items[y] = price;
if(price == 0)
{
double total;
total += price;
}
}
感谢任何帮助。谢谢!
【问题讨论】:
-
4 件事:1. 使您的数组大小初始化变量
const。 2. 您无法初始化大小为0的数组。 3. 当您增加x或y时,数组大小不会神奇地增加。 4.使用std::vector<std::vector<int>>和push_back()让它们动态增长。 -
您似乎使用随机数生成器编写了这段代码——几乎每一行都是错误的。请阅读有关 C++ 的书,而不是猜测。
-
另外,可变长度数组是刚性和非标准的,请考虑使用
std::vector<std::vector<int>>。 -
您实际上是在寻找将价格与输入的字符串值相关联的地图,对吧?
-
如果
items的大小为x,那么您只能访问0 到x-1 的范围。items[x]越界。
标签: c++ arrays xcode initialization