我有一个全局数组声明为
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/