0

我有这个代码

    int Iminente(char tab[3][3], char comp, char jog, char str[3][3]){

    int i, j, X = 0, val;
    char col[4], diag[2][4];

    strcpy(diag[0], &tab[0][0]); // Diagonal E-D C-B (= \ )
    strcat(diag[0], &tab[1][1]);
    strcat(diag[0], &tab[2][2]);

    strcpy(diag[1], &tab[0][2]); // Diagonal D-E B-C (= / )
    strcat(diag[1], &tab[1][1]);
    strcat(diag[1], &tab[2][0]);

    for(i = 0; i < 3; i++){
      strcpy(col, &tab[0][i]); // Colunas
      strcat(col, &tab[1][i]);
      strcat(col, &tab[2][i]);

      for(j = 0; j < 3; j++){
        if(strcmp(str[j], tab[i]) == 0){ // Verifica linhas
          Jogar(tab, comp, InvPosicao(i, j));

          return 1;
        }

        if(strcmp(str[j], col) == 0){ // Verifica colunas
          Jogar(tab, comp, InvPosicao(i, j));

          return 1;
        }

        if(!X){ // Verifica diagonais
          if(strcmp(str[j], diag[0]) == 0){
            Jogar(tab, comp, InvPosicao(j, j));

            return 1;
          }else if(strcmp(str[j], diag[1]) == 0){
            val = 2 - j;
            Jogar(tab, comp, InvPosicao(val, j));

            return 1;
          }
        }
      }
      X = 1;
    }

    return 0;
  }

该错误仅在我们到达指令时发生return 0。我找不到它的确切位置。我只能说所有信息都是由我(而不是用户)提供的,并且我根据我预测的长度定义了变量。
这是井字游戏的一部分。这是变量

tab - 3x3 table, each element is a char
comp - current computer char
jog - current player char
str - group of "strings" with 3 elements each with length 3 (null terminator not included)

i, j - iterators
X - "state" variable (not important)
val - not important
col - string with the current column
diag - group of "strings" with 2 elements each with length 4 (null terminator included)

价值观:

possible values for `str`:
    char perder[3][3] = {{' ', jog, jog}, {jog, ' ', jog}, {jog, jog, ' '}};
    char ganhar[3][3] = {{' ', comp, comp}, {comp, ' ', comp}, {comp, comp, ' '}};

value for `tab`:
    char jogo[3][3] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; // Elements can be ' ', 'O', or 'X'

values for `jog` and `comp`:
    'O' or 'X'

strcat()strcpy()函数有关系吗?

4

1 回答 1

0

正如@John3136 提到的,我的代码一团糟。
所以,为了解决这个问题,我实现了一个向字符串添加字符的函数:

void AdicionaCar(char *s, char c){

  int length = strlen(s);
  s[length] = c;
  s[length+1] = '\0';

}

strcatstrcpy用这个函数替换了 and 的所有实例。
然后初始化变量diagcol使用空终止符,以便它们可以成为字符串。将形式参数更改为指针(不是全部),现在函数头如下所示:

int Iminente(char (*tab)[3], char comp, char jog, char (*str)[3])
于 2018-02-14T15:44:30.233 回答