2 Dimensional array: strange values?
Jan 6, 2013 at 1:53am UTC
Hey guys,
I'm new to C++ and am getting confused while trying to use a 2d array.
Here's my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int testArr[5][5] = {0};
//test values
testArr[0][0] = 1;
testArr[0][1] = 2;
testArr[1][0] = 3;
testArr[1][1] = 4;
for ( i=0; i<=5; i++ )
{
for ( j=0; j<=5; j++ )
{
std::cout << "testArr[" <<i<<"][" <<j<<"] = " << testArr[i][j] << "\n" ;
}
}
And the output:
testArr[0][0] = 1
testArr[0][1] = 2
testArr[0][2] = 0
testArr[0][3] = 0
testArr[0][4] = 0
testArr[0][5] = 3
testArr[1][0] = 3
testArr[1][1] = 4
testArr[1][2] = 0
testArr[1][3] = 0
testArr[1][4] = 0
testArr[1][5] = 0
testArr[2][0] = 0
testArr[2][1] = 0
testArr[2][2] = 0
testArr[2][3] = 0
testArr[2][4] = 0
testArr[2][5] = 0
testArr[3][0] = 0
testArr[3][1] = 0
testArr[3][2] = 0
testArr[3][3] = 0
testArr[3][4] = 0
testArr[3][5] = 0
testArr[4][0] = 0
testArr[4][1] = 0
testArr[4][2] = 0
testArr[4][3] = 0
testArr[4][4] = 0
testArr[4][5] = -858993460
testArr[5][0] = -858993460
testArr[5][1] = -472153350
testArr[5][2] = 1964804
testArr[5][3] = 17324809
testArr[5][4] = 1
testArr[5][5] = 3823368
My main problem is that when set a value for the last column on row 0, it applys that same value to the first column on row 1 (seen above as with value: 3).
My second problem, which only seemed to happen during this test?(maybe it happened before but I missed it) is the crazy values in the last row?
If anyone could shed any light on my problem, I'd really appreciate it!
Thank you for your time.
Jan 6, 2013 at 2:05am UTC
You are overrunning the bounds of the array.
The idiom for doing something 5 times is :
for ( i=0; i<5; i++ ){}// no less than equal
the for loop ends when the end condition becomes false.
The array values go from 0 to 4.
When you specify [0][5] this really [1][1] because arrays are stored in linear order.
Same at the end values starting with [5] are past the end of the array - the last one is [4][4].
HTH
Jan 6, 2013 at 2:07am UTC
Wow, I feel foolish now.
Tottally missed that. Thanks a lot for clearing that up IdeasMan.
Jan 6, 2013 at 2:17am UTC
No worries - any time, just mark the thread as solved, and we will catch up with you next time - cheers.
Topic archived. No new replies allowed.