尝试实施泛洪填充时出现分段错误

Segmentation error trying to implement flood fill

我正在尝试为二维字符数组实现洪水填充算法。

问题是当我尝试 运行 时出现分段错误。 我尝试了多种方法,但我无法弄清楚问题出在哪里。

我正在尝试使用此输入:http://pastebin.com/raw/puexQfXY

错误截图:https://gyazo.com/b7e738d1d4f09a5d71a020b34a1e3b6c

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

void floodFill(int width, int height, char grid[width][height], char replacement, char target, int x, int y)
{
    if(x < 0 || x >= width || y < 0 || y >= height)
    {//check if out of array
        return;
    }
    if(grid[x][y] != target)
    {//check if on other than the target
        return;
    }
    grid[x][y] = replacement; //replace
    floodFill(grid, width, height, replacement, target, x + 1, y);//right
    floodFill(grid, width, height, replacement, target, x, y + 1);//down
    floodFill(grid, width, height, replacement, target, x - 1, y);//left
    floodFill(grid, width, height, replacement, target, x, y - 1);//up

}

int main()
{
    int width, height;
    scanf("%d", &width);
    scanf("%d", &height);
    char grid[width][height];
    for(int y = 0; y < height; y++)
    {
        getchar();//absorb newline
        for(int x = 0; x < width; x++)
        {
            grid[x][y] = getchar();
        }
    }

    floodFill(width, height, grid, 'O', '.', 2, 1);
    for(int y = 0; y < height; y++)
    {//print array
        for(int x = 0; x < width; x++)
        {
            putchar(grid[x][y]);
        }
        putchar('\n');
    }
}

你犯的错误是在函数本身内部调用函数。 只需看一下参数并尝试将它们与函数的原型匹配

您的代码

floodFill(grid, width, height, replacement, target, x + 1, y);//right
floodFill(grid, width, height, replacement, target, x, y + 1);//down
floodFill(grid, width, height, replacement, target, x - 1, y);//left
floodFill(grid, width, height, replacement, target, x, y - 1);//up

应该是

floodFill( width, height,grid, replacement, target, x + 1, y);//right
floodFill( width, height,grid, replacement, target, x, y + 1);//down
floodFill( width, height,grid, replacement, target, x - 1, y);//left
floodFill( width, height,grid, replacement, target, x, y - 1);//u