0

I'm ultimately trying to create a video game and am having this issue in C++ where the wrong array is being changed. Here's the code that's going wrong:

 #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;
 }

I get this as the output:

 Nathan
 Alyssa
 Alyssa

Something's not right, it should turn out:

 Nathan
 Alyssa
 Alex

In the Game, there are different types like legendary and xLegendary which have the same problem. I even checked if they had the same address and they didn't. What am I doing wrong?

1 Answer 1

5

This is a size 1 array:

string commonNames[] = {""};

You then access it as if it had more than one element. That out of bounds access is undefined behaviour. You might want to look at std::vector<std::string> instead. For example

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);
  }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.