通过指针访问数组时出现分段错误

时间:2017-03-30 09:50:39

标签: c arrays pointers operator-precedence

我有一个声明为

的全局数组
int Team1[12][8];

当我调用函数

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;
}

它填充数组直到位置[10],[3],然后看似[10],[4]我得到一个分段错误,我无法理解为什么。

2 个答案:

答案 0 :(得分:5)

检查数据类型。

teamToRead是指向int [12][8]数组的指针。

由于operator precedence,下标运算符与解引用的结合程度更高。

所以,在

的情况下
  *teamToRead[currentPlayersNumber][otherNumber] = 20;

你试图说出像

这样的话
  *(* ( teamToRead + currentPlayersNumber ) ) [otherNumber] = 20;

其中,指针算法变为非法,因为它们遵守指针类型,从而冒险越界。

要解决这个问题,您需要通过明确的括号来强制执行取消引用的优先级,例如

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

答案 1 :(得分:1)

另一个选择是放弃指向二维数组的指针,只使用指针(一维数组的第一个):

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;
}