Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 通过指针访问数组时出现分段错误_C_Arrays_Pointers_Operator Precedence - Fatal编程技术网

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

C 通过指针访问数组时出现分段错误,c,arrays,pointers,operator-precedence,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 other

我将一个全局数组声明为

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;
}
int readLineupB(int teamNr){
国际(*teamToRead)[12][8];
teamToRead=&Team1;

对于(int CurrentPlayerNumber=1;CurrentPlayerNumber请检查数据类型。

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

由于,下标运算符绑定的值高于取消引用的值

那么,万一

  *teamToRead[currentPlayersNumber][otherNumber] = 20;
你想说的是

  *(* ( teamToRead + currentPlayersNumber ) ) [otherNumber] = 20;
其中,指针算术变得非法,因为它们遵循指针类型,因此会越界

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

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

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

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;
}
int Team1[12][8];
int readLineupB(int teamNr){
//将teamToRead声明为指向8整数数组的指针
int(*teamToRead)[8];
//Team1属于int x[12][8]类型,很容易衰变
//至整数(*x)[8]
teamToRead=Team1;

对于(int currentPlayersNumber=1;currentPlayersNumberhow about
(*teamToRead)[currentPlayersNumber][otherNumber]=20;
?C数组从
0
开始建立索引,然后上升到
N-1
。@M.M已删除:D睡眠/咖啡太少。谢谢@SouravGhosh,括号解决了这个问题!关于数组从0开始的问题,我知道,我刚刚减小了“宽度”排除边缘错误的分配。我本不希望出现这种优先级,这当然可以解释错误。再次感谢。这种解决方案需要更少的书写,谢谢。但是,我更喜欢Sourav,因为它似乎更容易理解。人们会立即看到变量是指向二维数组的指针。