gpt4 book ai didi

c - c语言中的段错误。 (关于编程挑战 :PC/UVa IDs: 110102/10189 Minesweeper)

转载 作者:太空宇宙 更新时间:2023-11-04 07:24:29 24 4
gpt4 key购买 nike

您好,我正在尝试解决编程挑战 PC/UVa ID:110102/10189,称为 C 语言的扫雷器。示例输入和输出:

input|output
------------
4 4 |
*... |*100
.... |2210
.*.. |1*10
.... |1110

这是我的实现:

void increment_at(int **A, int x, int y){
if (x<0 || y<0 || *(*(A+y) + x) < 0) {
return;
}

*(*(A+y) + x) += 1;
}

void mine_found(int **A, int row, int col){

*(*(A+col) + row) = -1;

int x = row-1;
int y = col-1;
increment_at(A, x, y);

x = row-1;
y = col;
increment_at(A, x, y);

x = row-1;
y = col+1;
increment_at(A, x, y);

x = row;
y = col-1;
increment_at(A, x, y);

x = row;
y = col+1;
increment_at(A, x, y);

x = row+1;
y = col-1;
increment_at(A, x, y);

x = row+1;
y = col;
increment_at(A, x, y);

x = row+1;
y = col+1;
increment_at(A, x, y);
}




int main(int argc, const char * argv[])
{
int width, height;
scanf("%d %d", &height, &width);

if (width<1 || height<1) {
return -1;
}

int i, j;


int **result = calloc(height, sizeof(int *));

for (i = 0; i<height; i++) {
*(result + i) = calloc(width, sizeof(int));
}

char *input_row = calloc(width+1, sizeof(char));

for (i = 0; i < height; i++) {
scanf("%s", input_row);
for (j = 0; j < width; j++) {
char c = *(input_row + j);
if (c == '*') {
mine_found(result, j, i);
}
}
}

free(input_row);

for (i = 0; i < height; i++) {
for (j = 0; j< width; j++) {
int cell = *(*(result+i)+j);
if (cell == -1) {
printf("*");
} else {
printf("%d",cell);
}
}
printf("\n");
}


for (i = 0; i<height; i++) {
free(*(result+i));
*(result+i)=NULL;
}

free(result);
result = NULL;
return 0;
}

有时它会给出段错误。例如输入

3 5
...*.
.....
**...

它给出 Segmentation fault: 11。但它在输入时按预期工作:

3 3
*..
*..
...

最佳答案

increment_at功能你检查你不增加游戏计划之外的区域。因为它是你只检查两侧 ( x < 0 || y < 0 )。您还需要检查其他两侧 ( x >= width || y >= height )。

关于c - c语言中的段错误。 (关于编程挑战 :PC/UVa IDs: 110102/10189 Minesweeper),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19444583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com