Kys Plox Kys Plox - 12 days ago 7
C Question

Segmentation error trying to implement flood fill

I'm trying to implement flood fill algorithm for 2d array of characters.

The problem is when i try to run it i get a segmentation error.
I tried multiple things but i cant figure out whats the problem.

I'm trying with this input: http://pastebin.com/raw/puexQfXY

Screenshot of error: 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');
}
}

Answer

Mistake you have is done is while calling the function inside the function itself. Just take a lokk at parameters and try to match them with the protoype of the function

Your code

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

It should be

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