# Thread: help with an array

1. ## help with an array

hallo

i am new to C++
and i start learning array, and i played with it
i made a code that insert values to 2D array (arr[x][y])
the input is: 1 2 3 4 5 6 7 8 9
the output does show correctly
but at the end of the code when i check what value there are
in the 0,2 or 1,2 index i see a wrong values..

this is the code:

Code:
```#include <iostream>
using namespace std;

int main(void){

int arr[2][2];

for (int x = 0; x<=2; x++){
for (int y = 0; y<=2; y++){

cin >> arr[x][y];
cout << arr[x][y] << endl;

}
}

cout << "the arr value is: " << arr[0][2] << endl;
}```
index 0,2 should show me the value 3 but instead it show me 4
index 1,2 should show me the value 6 but instead it show me 7
the rest of the index show a correct values.

please help me understand what is wrong here

thank you

2. Did you notice you declared arr as:
Code:
`int arr[2][2];`
But you're trying to assign values to a 3x3 array?

3. Originally Posted by flp1969
Did you notice you declared arr as:
Code:
`int arr[2][2];`
But you're trying to assign values to a 3x3 array?

Hi
First thank you

Arr [2][2] is not :
0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2

???
Cause if I set the number [2] its mean 0 to 2 no?

4. Arr [2][2] is :
0,0 0,1
1,0 1,1

5. Originally Posted by danny191
Hi
First thank you

Arr [2][2] is not :
0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2

???
Cause if I set the number [2] its mean 0 to 2 no?
See your code:
Code:
```int arr[2][2];
...
for (x = 0; x <= 2; x++)
for (y = 0; y <= 2; y++ ) ...```
x and y goes from 0 to 2 (including 2), or 3 steps each dimension.. BUT, you are declaring an 2x2 array...

6. Cause if I set the number [2] its mean 0 to 2 no?
No. It means 2 in length. Two of them.

0 is the first
1 is the second
2 would be the third, but you don't have a third

You'd have to ask for [3] of them

7. thank you guys

i was confused thinking [2] mean index 0 , 1 , 2 ..
now that i correct the array to arr[3][3] its works good

8. Originally Posted by danny191
now that i correct the array to arr[3][3] its works good
That's good to hear. Having done that, you might want to change the relevant loop conditions to x < 3 and y < 3 respectively, and perhaps even replace the magic number 3 with two different constants.

Popular pages Recent additions