在C语言中,返回递归所需的硬编码数组是否正确?

q8l4jmvw  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(99)

我意识到我需要我的C函数返回2个值而不是一个,那么以这种方式返回硬编码数组是否正确呢?

int * funct(){
    if(condition1){
       return{1,1}
    }else{
       return{1,-1}
    }
}

我需要这个返回数组结构来实现我的极大极小算法。这里有一些上下文代码,但这不是必需的(上面的例子应该足以表达这个想法)。

//Requires: board, depth & true if we're playing max player/ false if min player 
//Effects: returns best score & col
int * minimax(int ** board, int depth, bool maxPlayer){
  int newscore;
  int * validLocations= getValidLocations(board);
  bool gameOver= gameOver(board);
  if (depth==0 || gameOver){
    if (gameOver){
      if(isWin(board, COMPUTER)){
      return {-1, +10000};
      }
    else if(isWin(board,PLAYER)){
      return {-1, -10000};
      }
    else{
      return {-1, 0};; //tie
      }
    }
    else{ //depth is 0
      return {-1, boardScore(AI)};
    }
  }
  if(maxPlayer){
    int val= INT_MIN;
    int bestCol= validLocations[0];
    int validLocationsIndex=0;
    int col= validLocations[0];
    while (col!=-1  && validLocationsIndex<7){
      int ** possibleBoard= copyBoard(board);
      insert(possibleBoard, col, COMPUTER);
      newscore= minimax(possibleBoard, depth-1, false)[1];
      freeBoard(possibleBoard);
      if (newscore>val){
        val= newscore;
        bestCol= col;
      }
      validLocationsIndex++;
      col= validLocations[validLocationsIndex];
      return {bestCol, newscore};
      
    }
  }
  else{
    int val= INT_MAX;
    int validLocationsIndex=0;
    int col= validLocations[0];
    while (col!=-1  && validLocationsIndex<7){
      int ** possibleBoard= copyBoard(board);
      insert(possibleBoard, col, PLAYER);
      newscore= minimax(possibleBoard, depth-1, true)[1];
      freeBoard(possibleBoard);
      if (newscore<val){
        val= newscore;
        bestCol= col;
      }
      validLocationsIndex++;
      col= validLocations[validLocationsIndex];
      return {bestCol, newscore};
    }
  }
}
djp7away

djp7away1#

1.在C语言中无法返回数组自动存储持续时间

  1. return {-1, boardScore(AI)};此语法错误
    1.可以使用struct s作为传递bt值的结构
    1.可以使用复合文字
typedef struct
{
    int data[2];
}mystruct;

mystruct funct(int condition)
{
    if(condition)
    {
       return (mystruct){{1,-1}};
    }else
    {
       (mystruct){{1, -1}};
    }
}

相关问题