Search code examples
carrayspointersoperator-precedence

Segmentation fault when accessing array via pointer


I have a global array declared as

int Team1[12][8];

When I call the function

int readLineupB(int teamNr){

      int (*teamToRead)[12][8];
      teamToRead = &Team1;

      for (int currentPlayersNumber = 1; currentPlayersNumber<11; currentPlayersNumber++) {
        for (int otherNumber = 1; otherNumber<7; otherNumber++) {
            *teamToRead[currentPlayersNumber][otherNumber] = 20;
        }
    } 
    return 1;
}

it fills the array until position [10],[3], then seemingly for [10],[4] I get a segmentation fault, and I cannot understand why.


Solution

  • Check the data types.

    teamToRead is a pointer to int [12][8] array.

    Due to operator precedence, the subscript operator binds higher that the dereference.

    So, in case of

      *teamToRead[currentPlayersNumber][otherNumber] = 20;
    

    you're trying to say something like

      *(* ( teamToRead + currentPlayersNumber ) ) [otherNumber] = 20;
    

    where, the pointer arithmetic becomes illegal as they honor the pointer type and thereby ventures out of bounds.

    To solve that, you need to enforce the precedence of the dereference by explicit parentheses, like

     (*teamToRead)[currentPlayersNumber][otherNumber] = 20;