Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

incrementing unsigned char *image

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading