越界访问,调试真的很头疼
访问以点(x,y)为起点的横纵10*10范围内的值,求和
我先写了这个,怎么都不对
for (int countY = 0 ; countY < 10 ;++countY,++y) { uchar *dst_ptr = (uchar *)(dst_gray->imageData + y * dst_gray->widthStep); for(int countX=0; countX < 10 ; ++countX,++x) { sum = sum + dst_ptr[x]; cout<<(int)(dst_ptr[x])<<" "; } cout<<endl; }
调试了2个小时,终于发现问题
X会一直++下去而不会回到行头
就好比是
1111111111
00000000001111111111
000000000000000000001111111111
0000000000000000000000000000001111111111
00000000000000000000000000000000000000001111111111
不用多久,X访问的位置就越界了
正确的:
for (int countY = 0 ; countY < 10 ;++countY,++y) { uchar *dst_ptr = (uchar *)(dst_gray->imageData + y * dst_gray->widthStep); for(int countX=0,xx=x; countX < 10 ; ++countX,++xx) { sum = sum + dst_ptr[xx]; cout<<(int)(dst_ptr[xx])<<" "; } cout<<endl; }