繁体   English   中英

我的扫雷代码在C中出现分段错误错误

[英]Segmentation fault error with my minesweeper code in C

因此,我一直试图解决这个问题,在这里我必须编写一个代码,计算一个假想雷场上某个点附近的地雷数量。 这是代码:

#include <stdio.h>
#include <stdlib.h>


int main(void) {
    int row;
    int col;
    int count;
    int mineCount = 0;
    int i;
    int j;

    // allocating memory

    scanf("%d %d", &row, &col);

    char **m = malloc(sizeof(char* ) * row);

    for(i = 0; i < row; i ++)
    {
        m[i] = malloc(sizeof(char) * (col + 1));        //empty minefield
    }

    //planting mines

    for(count = 0; count < row; count ++)
    {
        scanf("%s", m[count]);
    }

    // counting mines

    for(i = 0; i < row; i ++)
    {
        for(j = 0; j < (col + 1); j ++)
        {
            if(m[i][j] != 42)
                {
                    if(m[i-1][j] == 42)
                        mineCount += 1;
                    if(m[i+1][j] == 42)
                        mineCount += 1;
                    if(m[i][j+1] == 42)
                        mineCount += 1;
                    if(m[i][j-1] == 42)
                        mineCount += 1;
                    if(mineCount > 0)
                        m[i][j] = mineCount;
                }
        }
    }

    //printing out the minefield

    for(i = 0; i < row; i ++)
    {
        for(j = 0; j < col; j ++)
            printf("%c", m[i][j]);

        printf("\n");
    }


    return 0;
}

我将“ 5 5”作为第一个输入,对于雷区,我的输入将如下所示:

*....
..*..
...*..
.*...
....*

最后,我得到了“分段错误(核心已转储)”错误。 我一直在寻找答案,发现当我尝试访问无法访问的内容时会发生这种情况。 任何帮助,将不胜感激。 谢谢。

if(m[i-1][j] == 42)

if(m[i][j-1] == 42)

对于这些语句,您需要检查i和j是否不为0,否则您正在访问无效的内存

...*.. // 6 char long第三个输入将使

//planting mines
for(count = 0; count < row; count ++)
{
    scanf("%s", m[count]);
}

缓冲溢出并写一个额外的. 越界内存。

另外,假设您必须实现该功能,则我看不到任何free

看看if(m[i+1][j]) 如果i = row-1,则等于row。 但是,因为您仅分配了行值并且寻址从0开始,所以row-1是您可以寻址的最大值。 当i或j分别为零时,在if (m[i-1][j])if(m[i][j-1])也是如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM