变量初始化错误c ++

Posted

技术标签:

【中文标题】变量初始化错误c ++【英文标题】:variable initialization error c++ 【发布时间】: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. 当您增加xy 时,数组大小不会神奇地增加。 4.使用std::vector&lt;std::vector&lt;int&gt;&gt;push_back()让它们动态增长。 您似乎使用随机数生成器编写了这段代码——几乎每一行都是错误的。请阅读有关 C++ 的书,而不是猜测。 另外,可变长度数组是刚性和非标准的,请考虑使用std::vector&lt;std::vector&lt;int&gt;&gt; 您实际上是在寻找将价格与输入的字符串值相关联的地图,对吧? 如果items 的大小为x,那么您只能访问0 到x-1 的范围。 items[x] 越界。 【参考方案1】:

你的代码

int x = 0;
int y = 0;
int items[x][y] = ;

定义了一个变长数组items,C++ 标准不支持,只在特定的扩展中支持。为了克服这个问题,您必须将 xy 声明为 const(并且值显然 > 0)。

但我认为您使用了错误的数据结构,因为您似乎想将价格与水果名称相关联。 map&lt;string,double&gt; 更适合这项任务:

#include <iostream>
#include <map>

int main()
    std::string food;
    std::map<std::string,double> priceForFood;
    std::cout << "enter food and price or quit to finish:" << std::endl;
    while(std::cin >> food && food != "quit") 
        double price;
        if (std::cin >> price) 
            priceForFood[food]=price;
        
    
    for (auto pair : priceForFood) 
        std::cout << pair.first << " cost " << pair.second << std::endl;
    
    return 0;

输入:

enter food and price or quit to finish:
apples 100
oranges 200
quit

输出:

apples cost 100
oranges cost 200
Program ended with exit code: 0

【讨论】:

以上是关于变量初始化错误c ++的主要内容,如果未能解决你的问题,请参考以下文章

C语言程序调试,编译的结果总是说我的变量S没有初始化,但是我怎么改都是这个错误,请高手指点一二。

C++ 错误 C4700:使用了未初始化的局部变量“i”

C语言全局未初始化数据段分析

尝试使用 const 初始化变量时出现错误“初始化元素不是常量”

为什么在函数内初始化extern变量会产生错误?

C语言中结构体初始化的方法