分段错误:11 c ++错误

时间:2017-01-07 04:57:41

标签: c++ recursion

这是我第一次在这个论坛上提问,所以在这里。我正在为练习创建一个井字游戏,我正在使用枚举器和递归,因为我从来没有真正完成枚举,并且总是可以进行一些递归练习。无论如何,我刚刚完成编码,让player2随机移动并在之后大约3转它给出了一个分段错误,我无法弄清楚为什么......我希望你们能搞清楚并感谢你!

#include <iostream>
#include <string>
#include <cstdlib>

const int size = 3;

enum play {none,X,O};

void NPC(play (&board)[size][size],play player2) {
  srand(time(NULL));
  int tempx = rand() % 3;
  int tempy = rand() % 3;
  if(board[tempx][tempy] == none)
    board[tempx][tempy] = player2;
  else
    NPC(board,player2);
}

void getBoardState(play (&board)[size][size],int y,int x) {
  if(board[x][y] == none) std::cout << " ";
  else if(board[x][y] == X) std::cout << "X";
  else std::cout << "O";
}

void printboard(play (&board)[size][size]){
  int length = 4 * size - 1;
  for(int i = 1; i <= length; i++) {
    for(int j = 1; j <= length; j++) {
      if(i % 4 == 0 && j % 4 == 0) std::cout << "+";
      else if(i % 4 == 0) std::cout << "-";
      else if(j % 4 == 0) std::cout << "|";
      else if(i % 2 == 0 && j % 2 == 0) getBoardState(board,(i - 2)/4,(j - 2)/4);
      else std::cout << " ";
    }
    std::cout << std::endl;
  }
}

int main() {
  play player = O, player2 = X;
  bool over = false;
  play board[size][size];
  for(int i = 0; i < size; i++) {
    for(int j = 0; j < size; j++) {
      board[i][j] = none;
    }
  }
  std::string player1 = "";
  std::cout << "What would You like to be? An X or an O?" << std::endl;
  while(((player1 != "X") + (player1 != "O")) == 2) {
    std::cin >> player1;
    if(((player1 != "X") + (player1 != "O")) == 2)
      std::cout << "Invalid entry! Please enter X or an 0!" << std::endl;
    }
  if(player1 == "X") {
    player2 = O;
    player = X;}
  int tempx,tempy;
  while(!over) {
    std::cout << "Please enter an x and then a y (1 to " << size << ")" << std::endl;
    std::cin >> tempx;
    std::cin >> tempy;
    while(tempx > size || tempy > size || board[tempx-1][tempy-1] != none) {
      std::cout << "Invalid entry! Try again!" << std::endl;
      std::cin >> tempx;
      std::cin >> tempy;
    }
    board[tempx-1][tempy-1] = player;
    NPC(board,player2);
    printboard(board);
  }
  return 0;
}

1 个答案:

答案 0 :(得分:1)

您的递归中的堆栈空间不足,因为您每次都会调用srand(time(NULL))。随机数生成器只能在main中播种一次,而不能在NPC中播种。 time(NULL)返回几秒钟,因此它不经常更改(与递归函数调用的速度相比),这将消耗所有可用的堆栈空间。