user2326369
user2326369

Reputation:

Why does my code do assignments that I didn't write?

my array called tablero[2][2] is empty. When I try to assign a number in its [0][2] or [1][2] position, the [1][0] and the [2][0] positions are asigned too. I dont know why this happens

  void introducir_ficha(){
        int valido = 0;
        int pos_x, pos_y;
        while(valido == 0){
            printf("Introduce la posicion que quieres para la ficha \n");
            scanf("%d",&pos_x);
            printf("\n");
            scanf("%d",&pos_y);
            if(pos_x > 2 || pos_y > 2){
                printf("La posicion no es valida... \n");
            }else{
                valido = comprobar_hueco(pos_x, pos_y);
//comprobar_hueco just returns if this position is empty or not
                if(valido == 0){
                    printf("La posicion no es valida... \n");
                }
            }
        }
        printf("Posiciones %d %d \n",pos_x,pos_y);
        tablero[pos_x][pos_y] = 1;
    }

I hope u can help me.

Upvotes: 0

Views: 82

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311018

The problem is that acceptable indexes for your array are in the range [0, 1]. Arrays are placed in memory row by row. So your array will have representation in the memory as

tablero[0][0] tablero[0][1]
tablero[1][0] tablero[1][1]

When you try to access an element of the array using indexes [0][2] the compiler calculates the addres as 0 * sizeof( int[2] ) + 2 * sizeof( int ) (provided that the element type of the arrray is int). As the result it will calculate the address of the element that corresponds to indexes [1][0]

Upvotes: 1

Boann
Boann

Reputation: 50041

tablero[2][2] is a 2 by 2 array. Thus the four elements are [0][0], [0][1], [1][0], and [1][1]. There are no [0][2] or [1][2] elements.

If you try to use an index of 2, it will exceed the bounds of the row or column, and possibly wrap into the next row/column, or it will access memory outside the array entirely and may crash the program.

To use element indices from 0 to 2, you want a 3 by 3 array.

Upvotes: 9

Related Questions