I am trying to figure out how to apply the Sobel edge detection for a BMP image, which is a 2D array of BYTE values. When multiplying a pixel by the GX or GY kernel, if the pixel is on the edge of the image, I'm supposed to assume the missing pixels have the RGB values of 0.
Wanting to test my method of how to know if a pixel is outside the 2D array. This is what I came up with, but it seems like I am accessing indexes that are out of range.
int array [3][3]={{1,2,3},{4,5,6},{7,8,9}};
printf ("\n");
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
int yAxis[3]={i-1,i,i+1};
int xAxis[3]={j-1,j,j+1};
int y = yAxis[i];
int x = xAxis[j];
printf(" y: %i x: %i v: %i",y,x,array[y][x]);
}
printf("\n");
}
If I try to print array[-1][-1]
I get a compiling error:
arrayTest.c:27:14: error: array index -1 is before the beginning of the array [-Werror,-Warray-bounds]
But in the for loops, it seems to be printing the array value at index[-1][-1]
.
filter-more/ $ ./arrayTest
| y: -1 x: -1 v: 0 | y: -1 x: 1 v: 1 | y: -1 x: 3 v: 1
| y: 1 x: -1 v: 3 | y: 1 x: 1 v: 5 | y: 1 x: 3 v: 7
| y: 3 x: -1 v: 9 | y: 3 x: 1 v: -576368544 | y: 3 x: 3 v: 1
To be clear, all those values (v:)
will consistently show up except for y:3 x:1
that is the only value which will change every time the program is run.
So what am I missing that's going on here?
y: -1 x: -1
means you're accessingarray[-1][-1]
, as you said. Do you want to know howx
andy
ended up with the value-1
, or why the results of some out-of-bounds accesses change across runs and others don't, or why GCC doesn't catch the bug with-Warray-bounds
, or something else? $\endgroup$y:3 x:-1 v:9
: most likely, the values inarray
are stored in the memory sequentially, and this accesses the last element of the array. 2) The compiler doesn't catch it because at the moment of compilation it doesn't know that there may be out of bounds access. While it is possible to infer "out of bounds" for this particular example, due to certain reasons the compiler must stop the analysis at some point. $\endgroup$