I'm trying to repaint all the image pixels recursively but it fails because the stack overflows. But why?
void go( short x, short y ) {
if ( x < 0 || y < 0 || x >= _w || y >= _h ) return ;
_image[ x ][ y ] = someColor;
go( x + 1, y );
go( x - 1, y );
go( x, y - 1 );
go( x, y + 1 );
}
This function call will never stop.
void go( short x, short y ) {
if ( x < 0 || y < 0 || x >= _w || y >= _h ) return ;
_image[ x ][ y ] = someColor;
go( x + 1, y );
go( x - 1, y );
go( x, y - 1 );
go( x, y + 1 );
}
If you call your function with x=0,y=0 (go( 0, 0 );) it will do this
_image[ 0 ][ 0 ] = someColor;
go( 1, 0 );
go( -1, 0 );
go( 0, -1 );
go( 0, 1 );
OK now let's check the function call to go( 1, 0 );:
_image[ 1 ][ 0 ] = someColor;
go( 2, 0 );
go( 0, 0 ); //ohoh
go( 1, -1 );
go( 1, 1 );
So you can see that go( 0, 0 ) calls go( 1, 0 ) callsgo( 0, 0 ) calls go( 1, 0 ) callsgo( 0, 0 ) calls go( 1, 0 ) callsgo( 0, 0 ) calls go( 1, 0 ) callsgo( 0, 0 ) calls go( 1, 0 ) calls ....
That's why you have a stack overflow. You won't ever get out.
Why don't you just create 2 loops and iterate over these?
As your example always iterates x from 0 to _w and yfrom 0 to _hI would just get rid of these parameters at all.
You can just use this:
void go( short x, short y ) {
for(short x = 0; x < _w; x++) {
for(short y = 0; y < _h; y++) {
_image[ x ][ y ] = someColor;
}
}
}
I think you're missing one base case of initial value of _image array, as to stop re-filling same values over and over
if ( _image[x][y] != previousColor )
return;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With