C++ Basic Language Problem

Member
Posts: 281
Joined: 2009.04
Post: #1
Hello I have an infuriating (really) problem with a noughts-and-crosses C++ program. The details of the program are irrelevant but this is what I am doing:

Create array
Code:
int grid[2][2]

Get player's input into pos and then branch accordingly. This works well until this line is reached:
Code:
    grid[0][2] = X;
(X is a defined constant equal to 5)

Now look at the following screenshot:
[Image: 33c9q86.png]
(part of this image is cropped please open in a new window to see all of it)

Notice the points of CHECKPOINT A and CHECKPOINT B then look at the terminal output on the right. Somehow grid[1][0] changes! What is happening here?

~ Bring a Pen ~
Quote this message in a reply
Moderator
Posts: 697
Joined: 2002.04
Post: #2
Arrays in C++ are indexed from 0, so if you have an array with 2 elements, the legal indexes will be 0 and 1; writing to (the illegal) index 2 will write to memory elsewhere in your program, as you've discovered Wink Amending your declaration of "grid" as below…
Code:
int grid[3][3];
…will likely fix the bug.

Mark Bishop
--
Student and freelance OS X & iOS developer
Quote this message in a reply
Member
Posts: 281
Joined: 2009.04
Post: #3
Hahaha what a stupid mistake Rasp . Thanks a bunch.

~ Bring a Pen ~
Quote this message in a reply
Post Reply