c - 段错误: 11 C

标签 c segmentation-fault

我正在制作一个简单的命令行 Candy Crush 游戏。这是我下面的代码。我在 xCode 中编写它,然后使用 pico 在终端中运行它。游戏板打印正确,但板上没有 X。相反,打印板后会出现段错误。

//
// Assignment 3
//

#include <stdio.h>`enter code here`

//function headers
void displayOriginal (int img[10][10], int col, int row);

void removeOriginal (int img[10][10], int col, int row);

int main(){
  //declare variables and array
  int col = 0;
  int row = 0;
  int img[10][10];

  //call functions
  displayOriginal (img, col,row);    
  removeOriginal (img, col, row);        
  displayOriginal (img,col,row);

  return 0;
}

    //function for displaying gameboard
void displayOriginal (int img[10][10], int col, int row){   
  for(row = 0; row < 10; row++){//to create rows 0-9
    for(col = 0; col < 10; col++){//to create columns 0-9
      scanf("%d", &img[row][col]);
    }
  }
  printf("  0 1 2 3 4 5 6 7 8 9\n");//adds labels to x axis

  for(row = 0; row < 10; row++){
    printf("%d", row);//add labels to y axis

    for(col = 0; col < 10; col++){                  
      if (img[row][col] == 1){ //red
        printf("\x1b[41m  ");
      } else if (img[row][col] == 2){//green
        printf("\x1b[42m  ");
      } else if (img[row][col] == 3){//purple
        printf("\x1b[43m  ");
      } else if (img[row][col] == 4){//blue
        printf("\x1b[44m  ");
      } else if (img[row][col] == 5){//magenta
        printf("\x1b[45m  ");
      } else if (img[row][col] == 0){
        printf("XX");
      }
      printf("\x1b[m"); //white
    }
    printf("\n");            
  }
}

//function to label where the X's go
void removeOriginal (int img[10][10], int col, int row){
  //variables
  int previous = -10;
  int temp;
  int tally = 1;

  for(row = 0; row < 10; row++){
    for(col = 0; col < 10; col++){
      if (previous == img[row][col]){//if previous block =current then add 1
        tally++;
      } else {
        tally = 1;//return to 1 if previous does not equal current
      }

      if (tally >= 3){
        previous = img[row][col];
        for (temp = (tally-1); temp >= 0; temp--){
          img [row-temp][col] = 0;
        }
      } else {
        previous = img [row][col];
      }
      printf("Row %d Col %d Tally %d", row, col, tally);
    }
  }
}

最佳答案

您确定本节中的 row >= temp 吗?如果不是,img[-1][col] 将导致段错误。

if (tally >= 3)
            {
                previous = img[row][col];
                for (temp = (tally-1); temp >= 0; temp--)
                {
                    img [row-temp][col] = 0;
                }
            }

关于c - 段错误: 11 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29021075/

相关文章:

c - C 中 LAPACKE dgels_ 的段错误

c++ - 可以在不取消引用的情况下增加指针仍然是段错误或具有其他(未)定义的肮脏吗?

c - 通过C套接字发送图像

c - 如何从 C 代码中找到 kernel.shmmax 的值

qt - 如何通过远程服务器运行 GUI

c - 数据处理代码中的段错误

c++ - 参数 C++ 中大字符串的段错误

c - 设置中断以监视引脚变化

c - 无法连接两个 char * 指针值?

c - 从 C 中的队列中删除项目的线程