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

时间:2013-10-18 08:05:06

标签: c

您好我试图用C语言解决编程挑战PC / UVa ID:110102/10189,称为Minesweeper。样本输入和输出:

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
*..
*..
...

1 个答案:

答案 0 :(得分:3)

increment_at功能中,您检查不会增加游戏计划之外的区域。因为它只检查双方(x < 0 || y < 0)。您还需要检查另外两面(x >= width || y >= height)。