简体   繁体   中英

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.

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;

Another option is to forgo the pointer to 2-dimensional array, and just use pointer to (first of array of) one-dimensional array:

int Team1[12][8];

int readLineupB(int teamNr){
    // declare teamToRead as a pointer to array of 8 ints
    int (*teamToRead)[8];

    // Team1 is of type int x[12][8] that readily decays 
    // to int (*x)[8]
    teamToRead = Team1;

    for (int currentPlayersNumber = 1; currentPlayersNumber<11; currentPlayersNumber++) {
        for (int otherNumber = 1; otherNumber<7; otherNumber++) {
            // no dereference here.
            teamToRead[currentPlayersNumber][otherNumber] = 20;
        }
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM