Reputation: 689
void GameBoard::enterShips()
{
char location[1];
int ships = 0;
int count = 1;
while(ships < NUM_SHIPS)
{
cout << "Enter a location for Ship " << count << ": ";
cin >> location;
cout << endl;
Grid[location[0]][location[1]] = SHIP;
ships++;
count++;
}
}
Im writing a battleship game. I have the board layouts working and the computers randomly generated ships. Now I am working on this method to prompt the user to enter coordinates for the ships When I run the program, it allows me to enter 5 ships. When I enter the 6th ship, it gives me this error.
Stack around the variable location was corrupted.
Ive looked for answers online and have not found anything exclusive.
Any help would be appreciated.
Upvotes: 8
Views: 74065
Reputation: 9687
You are prompting the memory address of location
array to your user. You should ask location indices separately:
void GameBoard::enterShips()
{
int location[2];
int ships = 0;
int count = 1;
while(ships < NUM_SHIPS)
{
cout << "Enter a location for Ship " << count << ": ";
cin >> location[0];
cin >> location[1];
cout << endl;
Grid[location[0]][location[1]] = SHIP;
ships++;
count++;
}
}
Notice int location[2];
since an array of size 1 can only hold one element. I also changed the element type to int. Reading char's from the console will result in ASCII values, which are probably not what you want.
Upvotes: 7
Reputation: 355049
cin >> location;
location
is an array of one char
. This can't succeed because when you read from a stream into a char
array, a null terminator has to be added (which takes one character). You will inevitably overrun the bounds of the array.
You can use a std::string
, which will help you avoid any buffer overrun issues:
std::string location;
if (!(std::cin >> location)) {
// handle input error
}
Note also that you probably need to convert the string representations of the numbers into numeric values. You can easily do this by reading from the stream into two int
objects instead:
int x_location, y_location;
if (!(std::cin >> x_location >> y_location)) {
// Handle input error
}
if (x_location >= X_DIMENSION || x_location < 0 ||
y_location >= Y_DIMENSION || y_location < 0) {
// Handle out-of-range error
}
// use x_location and y_location
Upvotes: 4
Reputation: 20609
You made the location
variable only able to hold a single character. You access it expecting it to hold at least 2 characters. If you're using cin and expecting to read exactly two characters, a better method would be:
char locationX, locationY;
// ...
std::cin >> locationX >> locationY;
// ...
Grid[locationX][locationY] = SHIP;
Upvotes: 3