Array Help

Started by
5 comments, last by Balrog30 18 years, 8 months ago
Im having a problem with a 2d array ttGrid[2][2] I init the int array to Zeroes but if i set the [0][2] index to a value, the value will spill over into the [1][0] index. so in the below example you can see im setting [0][2] to 9, well both this and [1][0] will have the value 9 now, im at a loss!...
[source="cpp"]
class game {

public:
	game();
	void flipPlayer();
	void printBoard();
	void playerMove();
	char validMove(int);
	void updateBoard(int);
	void checkWinner();

private:
	int currPlayer;
	int ttGrid[2][2];
};

game::game()
{
//
//Init Grid to Zeroes
//Init Vars 
	int k = 0;
	for (int i = 0; i <= 2; i++)
	{
		for(int j = 0; j <= 2; j++)
		{
			ttGrid[j] = 0;
		}
	}
		ttGrid[0][2] = 9;  // Put this here to test
                cout << ttGrid[0][2];
		cout << ttGrid[1][0];
	currPlayer = 1;
}


Advertisement
array[2][2] creates a 2x2 array, or 4 elements.

0,0; 0,1; 0,2; 1,0; 1,1; 1,2; 2,0; 2,1; 2,2; 9 elements...

Quote:Original post by Telastyn
array[2][2] creates a 2x2 array, or 4 elements.

0,0; 0,1; 0,2; 1,0; 1,1; 1,2; 2,0; 2,1; 2,2; 9 elements...





which is what i want, basically a tic tac toe board

but, if i set the index 0,2 to something, 1,0 gets the same value
i see the same behavior with index 1,2 now 2,0 will gets the same value, its like the value is spilling over in memory or something?

if you want 9 elements, make 9 elements.

array[3][3];

And yes, it's similar to a simple buffer overrun, and the source of nearly every virus, worm, and exploit in the past 2 decades.
You only have 4 elements not 9 like in tic-tac-toe.

[2][2] = [0][0],[0][1],[1][0],[1][1]

There is no [0][2] as that would be the third element and therefore instead points to [1][0].

Use ttGrid[3][3]

Edit: Damn it, too slow :(
oh my god my brain is fried....
i completely forgot that the subscript is the actual number of indexes you want, so i was thinking [2] or 0,1,2 in the subscript gives me 3x3

bah, thanks guys sorry for wasting time
Never think of it as wasting anyone's time. You may asked a question 10 other people were too shy to ask, and now they know the answer.
-----------------------------"I think perhaps you do not understand. People's whole lives do pass before their eyes before they die. The process is called living." -The Death of DiscworldFrom Terry Pratchett's "The Last Continent"

This topic is closed to new replies.

Advertisement