Search code examples
c++pointerspointer-arithmetic

Can you please help explain this code?


I have this function that I'm trying to convert but I just cant understand what is happening in some parts of the code. Could anyone please help me out and explain the code. I just want to know what they do with the pointers. There are some blank comments in the code where they do hell with the pointers, i just dont get it.

Any help appreciated.

WORD** m_Pixels;

int pixel(int x, int y)
{

    if (x<0 || y<0 || x>=m_Width || y>=m_Height)
        return -1;

    WORD    *pPixels = m_Pixels[y];

    //
    int count = *pPixels++;

    int index = 0;

    register int i;

    if (count > 0)
    {
        i = count;
        do {
            // 
            index += *pPixels++;

            if (x < index)
            {
                return -1;
            }

            //      
            index += *pPixels;

            // 
            pPixels += *pPixels;

            pPixels++;


            // 
            index += *pPixels;

            // 
            pPixels += *pPixels;

            pPixels++;

            if (x < index)
            {
                return pPixels[x-index];
            }
        } while (--i);
    }

    return -1;
}

Solution

  • int count = *pPixels++;
    

    Dereferences the pPixels pointer to get the value and assigns it to count and increment the pointer - this will make the pointer to point to the next element in the array (m_Pixels)


    index += *pPixels++;
    

    Increment index with the value, pointed by pPixels and increment the pointer - this will make the pointer to point to the next element in the array


    pPixels += *pPixels;
    pPixels += *pPixels;
    

    Move the pointer X positions ahead, where X is the value, pointed by pPixels