我正在制作一个简单的命令行糖果粉碎游戏。这是我下面的代码。我用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 9n");//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);
}
}
}
您确定本节中的行>= temp吗?如果不是,img[-1][col] 将导致分段错误。
if (tally >= 3)
{
previous = img[row][col];
for (temp = (tally-1); temp >= 0; temp--)
{
img [row-temp][col] = 0;
}
}