Reputation: 203
My question is much like this one Setting a value in a 2d array causes others in array to change, however it does not solve what I have here.
I am also trying to make a game field with a 2D array, currently full of '#'. I am trying to get the top left corner to become '.' (but leaving a border or '#' around the field, so its 1, not [0][0]).
However, whatever I tried so far always turns two spots into '.':
################.###
#.##################
####################
#####D##############
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
This doesn't make any sense, since (as far as I can see) I am not overflowing anywhere into a RAM slot, and even when I set map[1][1].symbol = '.';
it still gives those two spots as '.', though there is only one location being changed.
Code (partial):
#include <ctime>
#include "stdlib.h"
// Create structure for map tiles
struct mapTile{
char symbol;
bool walkable;
};
//Set map Width and Height and create empty array
//I did it like this so I can change the width and height later via ingame menu
int const mapWidth = 20;
int const mapHeight = 15;
mapTile map[mapWidth][mapHeight];
char x = 1;
char y = 1;
void generateField(){
srand(time(NULL)); //not used yet
//Set whole field to '#'
for(int y = 0; y < mapHeight; y++){
for(int x=0; x < mapWidth; x++){
map[y][x].symbol = '#';
map[y][x].walkable = false;
}
}
//Open up route to walk
map[3][5].symbol = 'D';
map[y][x].symbol = '.';
map[y][x].walkable = true;
};
void printField(){
//print each symbol of the field
for(int y = 0; y < mapHeight; y++){
for(int x=0; x < mapWidth; x++){
cout << map[y][x].symbol;
}
cout << endl;
}
}
Upvotes: 1
Views: 330
Reputation: 537
first of all you are going out of the bounds of the array. The limit of your array is [mapWidth][mapHeight]. But in the initialization loop you are iterating the [y][x] - y till mapHeight and x till mapWidth.
And the second reason is, the value of x and y has already changed when you are initializing it to '.' and false. Please see the array size and work accordingly.
Upvotes: 2
Reputation: 7017
In both your for-loops you access the map as [height][width], however you define it as [width][height].
Changing it solves the problem (on my machine).
Upvotes: 4