0

I want to make a simple programm that shows a square of 16 'X' and that you can change specific coordinates. Everything is finished and i dont get any bugreports but in the programm things are very strange. what i should get is easy

 XXXX                              
 XXXX
 XXXX
 XXXX

and if i change 1,1 to A i should have this

 AXXX
 XXXX
 XXXX
 XXXX

but what i see when i run the program is this:

 XXXX
 XXXX
 XXXX
 @

well what is with the fourth line? there is a smiley in the first spot (i used an @) and the rest is empty. when i change 1,1 to anything, 3,4 changes too. everything else works properly. and if i try to change something in the fourth line the program crashes. if you want to test it yourself i can upload the .exe #include

using namespace std;

int main()
{
    for (;;) {
    int eingabe1;
    int eingabe2;
    char neueingabe;
    char array[4][4];
    array[1][1] = 'X';
    array[1][2] = 'X';
    array[1][3] = 'X';
    array[1][4] = 'X';
    array[2][1] = 'X';
    array[2][2] = 'X';
    array[2][3] = 'X';
    array[2][4] = 'X';
    array[3][1] = 'X';
    array[3][2] = 'X';   
    array[3][3] = 'X';
    array[3][4] = 'X';
    array[4][1] = 'X';
    array[4][2] = 'X';
    array[4][3] = 'X';
    array[4][4] = 'X';
    cout << "koordinaten eingeben" << endl; 
    cin >> eingabe1;
    cin >> eingabe2;
    cout << array[eingabe1][eingabe2] << endl;
    cout << "neueingabe eingeben" << endl;
    cin >> neueingabe;
    array[eingabe1][eingabe2] = neueingabe;
    cout << array[eingabe1][eingabe2]<< endl;
    }
    return 0;
}

i hope you can help

  • 8
    Arrays in C, C++ *et al* use indices starting at 0. – Paul R Jan 23 '13 at 14:29
  • 2
    You should start by reading some [C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), really. –  Jan 23 '13 at 14:35
  • you make me feel so stupid with 1 line :D – Robert Wegner Jan 23 '13 at 14:35
  • 1
    thats just what im doing. – Robert Wegner Jan 23 '13 at 14:36
  • Also note that "bug reports" generally come from humans, or other entities *testing* your software. The compiler can only generate warnings and errors if your code doesn't comply with the language specifications, but it cannot tell you "it doesn't do what it should". The behavior you're describing is clearly a bug, so that's a bug report right there. – unwind Jan 23 '13 at 14:37

2 Answers2

3

YOU ARE WRITING PAST YOUR ARRAY!

Arrays in C/C++/C#/Java and most other languages start their numbering with 0.

So for

int arr[4];
// you have:
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
//arr[4]= A REALLY BIG ERROR;
Tadeusz Kopec for Ukraine
  • 12,283
  • 6
  • 56
  • 83
Dariusz
  • 21,561
  • 9
  • 74
  • 114
1

Start the indices at 0. So the max index is 3,3; the lowest is 0,0. Accessing other values leads to random behavior - in the best case it crashes your program.

Tobias Langner
  • 10,634
  • 6
  • 46
  • 76