incrementing unsigned char *image

Advertisements
void draw(unsigned char *image)
    {
        for (int y = 0; y < HEIGHT; y++)
        {
            for (int x = 0; x < WIDTH; x++)
            {
                if (someCondition)
                {
                    int red = x * 256 / WIDTH;
                    int green = 255;
                    int blue = y * 256 / HEIGHT;

                    image[0] = (unsigned char)blue;
                    image[1] = (unsigned char)green;
                    image[2] = (unsigned char)red;
                }
                else
                {
                    image[0] = 0;
                    image[1] = 0;
                    image[2] = 0;
                }
                image += 3;
            }
        }
    }

What does incrementing image+=3; actually do here. I’m trying to convert the same c++ code to C#, but unable to achieve this. I’m using byte[] image in C#, now how should I do image+=3 in C#. Is it scaling the image?

>Solution :

From the code it is evident that the pointer points to an element of an array of unsigned char:

[ ][ ][ ][ ] ........... [ ]

 ^
 |
 image

Next consider that image[i] is equivalent (really equivalent, that is how it is defined) to *(image + i), ie it increments the pointer by i and dereferences it. You can write image[0] to get the element image points to. You can type image[1] to get the next element in the array.

Lets call the actual array x then you can access its elements via incrementing image like this:

x[0]      x[1]     x[2]      x[3]          x[4]          x[5]
image[0]  image[1] image[2]
                             (image+3)[0]  (image+3)[1]  (image+3)[2]

In other words, the author could have used some offset in the outer loop which increments by 3 in each iteration and then instead of image[ i ] they would have used image[ i + offset ]. Instead they choose to increment image which has the same effect.

Leave a ReplyCancel reply