How arrays work or are stored in memory?

I was working with outputting an array and I noticed a funny thing happen when I got a for loop to output more 'rows' than the array had. It repeated the array as it went along, but one row higher? Why exactly did it do this?

Code for an example of it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
char arr[11][20] ={
{"OOOOOOOOOOOOOOOOOOO"},
{"OOOOOOOOOOOOOOOOOOO"},
{"OOOOOOOOOOOOOOOOOOO"},
{"OOOOOOOOOOOOOOOOOOO"},
{"OOOOOOOOOOOOOOOOOOO"},
{"OOOOOOOOOOOOOOOOOOO"},
{"OOOOOOOOOOOOOOOOOOO"},
{"OOOOOOOOOOOOOOOOOOO"},
{"OOOOOOOOOOOOOOOOOOO"},
{"OOOOOOOOOOOOOOOOOOO"},
{"OOOOOOOOOOOOOOOOOOO"}};

	for(int col=0;col<=11;col++)
	{
		for(int row=0;row<=40;row++)
    {

	     HANDLE hConsole;
         hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	     SetConsoleTextAttribute(hConsole, FOREGROUND_RED | BACKGROUND_BLUE);

		 cout<<arr[col][row];
	}
		cout << endl;
	}

	cin.ignore( INT_MAX, '\n' );
It is laid out in contiguous memory with arr[0][0] residing at the lowest memory address and arr[10][19] at the highest.

The compiler simply computes the memory address of arr[n][m] by taking the address of arr[0][0] and offsetting it by ( n*20 + m ) * sizeof( char ) bytes.

Topic archived. No new replies allowed.