문제

I'm trying to fill zero regions in a matrix using memset() in this way:

unsigned short *ptr;
for(int i=0; i < nRows; ++i)
{
    ptr = DepthMat.ptr<unsigned short>(i); /* OCV matrix of uint16 values */
    for(int j=0; j<nCols; ++j)
    {
        uint n=0;
        if(ptr[j] == 0) /* zero region found */
        {
            d_val = ptr[j-1]; /* saves last non-zero value */
            while(ptr[j+n] == 0) 
            { /* looks for non zero */
                ++n;
            }
            d_val = (d_val < ptr[j+n] ? d_val : ptr[j+n]);
            memset( ptr+j, d_val, n*sizeof( ptr[0]) );
            j += n;
        }
    }
}

I look for sequences of zero, then I store the positions (ptr+j-1 and ptr+j+n) and the values of the zero regions boundaries, and finally I use memset() to replace the zeros with d_val. The problem is that when I check the values stored they don't match with d_val, for example, I put the value '222' but I get '57054'. Any clue?

도움이 되었습니까?

해결책

The value argument to memset() is only a single byte, even though the type for the argument is int.

The manual page describes the function as:

memset - fill memory with a constant byte

So, no more than the least-significant 8 bits of d_val will be written to memory. Since you're treating the memory as an array of short, you get "mangled" values that consist of the same byte repeated through the bytes of the short.

In ... short, don't do this; use a for loop to do a repeated write of actual shorts.

다른 팁

memset writes one char at a time, while you're accessing them as short. 57054 = 222*256+222

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top