Question about two dimensional arrays

So I am just learning about two dimensional arrays and started to play around with the implementation and found something weird. Why is it that when incrementing the column one by one, every number is displayed in the dialog box.....but when incrementing the rows one by one, only the first number in each row is displayed. It's at line 14. Thanks for any response.

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
#include <iostream>   //study this
#include <string>
#include <cstring>
#include <iomanip>
using namespace std;

int main()
{
    int temp[3][4] =    {{6, 8, 12, 9},
                        {17, 5, 10, 6},
                        {14, 13, 16, 20}};
    int row=0, col=-0;

    for(col=0; col<12;col++) //when I change col to row I get crazy numbers 
    cout << temp[row][col] << " ";
    cout<<endl<<endl<<endl;

    for(row = 0; row<3;row++) //output like a table
    {
        for(col =0;col<4;col++)
            cout << setw(2)<<temp[row][col]<<" ";
            cout << endl;
    }

    return 0;
}



Output when the variables in line 14 are changed to row:
6 17 14 0 3 2686824 6690480 -1601518058 0....and three other odd numbers
I understand the first 3 numbers above but what are the others?


Output when the variables in line 14 are changed to column:
6 8 12 9 17 5 10 6 14 13 16 20

How does incrementing the column variable output the numbers but incrementing rows doesn't
Last edited on
i hope this code makes you understand, if you still have issues just ask.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
char temp[3][4];

for(int i=0;i<3;i++)
{
	for(int j=0; j<4;j++)
	{
		cout<<"Enter Element for "<<i+1<<" row and "<<j+1<<" column"<<endl; 
		cin>>temp[i][j];
	}
}

for(int i2=0;i2<3;i2++)
{
	for(int j2=0; j2<4;j2++)
	{
			cout<<temp[i2][j2]<<"	";
	}
	cout<<endl;
}
In each row the array has only four columns. So the llop

for(col=0; col<12;col++) //when I change col to row I get crazy numbers
cout << temp[row][col] << " ";

is incorrect

That is when you change col to row each row increment results in that you bypass 4 * iszeof( int ) memory locations.

temp[row] has type of array int[4]
So if temp[0] points to for example the address 0, then temp[1] will point to 0 + 4*sizeof( int ) that is 16. temp[2] will point to 16 + 16 = 32 and so on.
Last edited on
Thanks for the response but despite line 14 being wrong, the program still prints out every number which is why it is so weird. That's the crutch of my problem......just curious as to how it manages to do so.


EDIT: I just got the end of your last message vlad from moscow. I get it now. Thanks again
Last edited on
Arrays are placed in memory rows by rows. Your original array has only 3 rows. So when you set index of the row greater than 2 you are trying in fact to acces memory beyond your array.
Topic archived. No new replies allowed.