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

标签 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] 我遇到了段错误,我不明白为什么。

最佳答案

检查数据类型。

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

由于operator precedence ,下标运算符的绑定(bind)高于取消引用。

所以,如果是

  *teamToRead[currentPlayersNumber][otherNumber] = 20;

你想说些类似的话

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

其中,指针运算变得非法,因为它们遵循指针类型并因此冒险越界。

要解决这个问题,您需要通过显式括号强制取消引用的优先级,例如

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

关于c - 通过指针访问数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43114278/

相关文章:

将文件指针传递给方法时出现 C 段错误

javascript - Node Js Transformation JSON by JSON key

java - 简单 ViewPager - 单一布局

c - 将指针转换为 void* 然后与 NULL 进行比较是否安全

C:程序在尝试释放 2D 数组本身时崩溃

c - 冒泡排序外循环和N-1

c - 指针未返回正确的值

arrays - 将特定元胞数组元素转换为数组

pointers - 空指针定义在计算机的哪一层?

c - 查找数组中输入数字的中位数