【问题标题】:C++ changing value of wrong arrayC ++更改错误数组的值
【发布时间】:2014-03-08 16:08:38
【问题描述】:

我最终试图创建一个视频游戏,并且在 C++ 中遇到了这个问题,其中更改了错误的数组。这是出错的代码:

 #include "stdafx.h"
 #include <iostream>
 #include <string>

 using namespace std;

 string commonNames[] = {""};
 string xCommonNames[] = {""};

 int commonIndex = 0;
 int xCommonIndex = 0;

 void placeName(string name, string placement)
 {
if(placement == "common"){
    commonNames[commonIndex] = name;
    commonIndex++;
}
else if(placement == "xCommon"){
    xCommonNames[xCommonIndex] = name;
    xCommonIndex++;
}

 }

 int _tmain(int argc, _TCHAR* argv[])
 {

placeName("Nathan","common");
placeName("Alex","xCommon");
placeName("Alyssa","common");


cout << commonNames[0] << endl;
cout << commonNames[1] << endl;
cout << xCommonNames[0] << endl;

system("pause");
return 0;
 }

我得到这个作为输出:

 Nathan
 Alyssa
 Alyssa

有些不对劲,结果应该是:

 Nathan
 Alyssa
 Alex

在游戏中,传奇和xLegendary等不同类型存在相同的问题。我什至检查了他们是否有相同的地址,但他们没有。我做错了什么?

【问题讨论】:

    标签: c++ arrays string visual-c++


    【解决方案1】:

    这是一个大小为 1 的数组:

    string commonNames[] = {""};
    

    然后您访问它,就好像它有多个元素一样。越界访问是未定义的行为。您可能想查看std::vector&lt;std::string&gt;。例如

    std::vector<std::string> commonNames;
    std::vector<std::string> xCommonNames;
    
    void placeName(const std::string& name, const std::string& placement)
    {
      if(placement == "common"){
        commonNames.push_back(name)
      }
      else if(placement == "xCommon"){
        xCommonNames.push_back(name);
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 2014-05-09
      • 1970-01-01
      • 2018-11-14
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多