2016-11-27 65 views
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'); 
    } 
} 
+1

你的編譯器甚至不應該編譯。嗯,試了一下,它編譯了8個警告。如果您沒有看到警告,請使用'-Wall' for gcc,clang或'/ W4' for microsoft再次嘗試。 – user3386109

+0

另外:或者將'getchar'向下移動幾行到循環內部,或者轉儲它並使用'scanf(「%c」,&grid [x] [y]);'(注意消耗前導空白的空間) 。 –

+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 

的protoype匹配他們應該

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 
+0

TYSM,我在我的程序中的其他事情隧道太多,沒有意識到這個明顯的錯誤。當其他人查看代碼時,它非常有用 –