我试图为2d字符数组实现泛洪填充算法。
问题是当我尝试运行它时会出现分段错误。 我尝试了很多东西,但我无法弄清楚问题是什么。
我尝试使用此输入: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');
}
}
答案 0 :(得分:2)
在调用函数本身内部的函数时,您已完成的错误。 只需在参数上取一个lokk并尝试将它们与函数的原型匹配
您的代码
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