1
我正在尝试为二维数组字符实现泛洪填充算法。尝试实施泛洪填充的分段错误
问题是,当我尝试运行它时,我得到了分段错误。 我尝试了多件事,但我无法弄清楚最新的问题。
我试图与该输入: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');
}
}
你的编译器甚至不应该编译。嗯,试了一下,它编译了8个警告。如果您没有看到警告,请使用'-Wall' for gcc,clang或'/ W4' for microsoft再次尝试。 – user3386109
另外:或者将'getchar'向下移动几行到循环内部,或者转储它并使用'scanf(“%c”,&grid [x] [y]);'(注意消耗前导空白的空间) 。 –
这是什么原因?没有罪恶我只是不明白为什么这样做,因为它现在工作 –