string and array

Hi I would like to know what is the problem with this:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
char square[7][7],x,y;
string command;
//start:
for (x=1;x<9;x++)
{
for (y=1;y<9;y++)
{
square[x][y] = 'x';
}
}
getline(cin,command);
if (command.substr(0,5) == "print")
{
for (x=1;x<9;x++)
{
for (y=1;y<9;y++)
{
cout << square[x][y];
}
cout << "\n";
}
}
}

And what i get is:

xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xx rint
xxxxxxx (there is a space at the begining of this line)

When in my understandin should be a 8x8 block of "x".
I think it'a about memory allocation but couldn't find how to fix it.
Any help would be appreciated.
Last edited on
You are attempting to access elements of your array that are out of bounds. The 2D array "square" is declared with dimension 7 by 7. The elements of this array may be accessed using square[i][k] where i and k are elements of the set of integers {0,1,2,3,4,5,6}. Try this alternative:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <sstream>
using namespace std;

int main() {
	char square[7][7];
	int x, y;
	string command;
	for (x=0;x<7;x++) {
		for (y=0;y<7;y++) {
			square[x][y] = 'x';
		}
	}
	getline(cin,command);
	if (command.substr(0,5) == "print") {
		for (x=0;x<7;x++) {
			for (y=0;y<7;y++) {
				cout << square[x][y];
			}
			cout << "\n";
		}
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
	char square[7][7];
	string command;
	//start:
	for (int x=0;x<7; x++) {
		for (int y= 0;y < 7; y++) {
			square[x][y] = 'x';
		}
	}
	getline(cin,command);
	if (command.substr(0,5) == "print"){
	   for (int x=0; x<7; x++) {
		   for (int y=0; y<7; y++) {
               cout << square[x][y];
            }
            cout << "\n";
        }
    }

	return 0;
}


I do not understand what you're trying to do.
Oh... ye the was 2 missing. As I can see the ++ affects before the value is used in the array.
Aren't the values of a [7] array 0, 1 ,2 ,3 ,4 ,5 ,6 ,7?
Thanks that was the problem, as you can notice im new, my 3rd day of learning and maybe a bit tired.
No, you are missing the point. Read this: http://www.cplusplus.com/doc/tutorial/arrays/
good luck :)
Topic archived. No new replies allowed.