0

As above, I'm trying to edit a bit of code I wrote last week, the old code:

    char *pixel_b = NULL;
    char *pixel_g = NULL;
    char *pixel_r = NULL;

    for (i=0;i<416;i++)
    {
        for (j=0;j<576;j++)
        {
        pixel_b = &framebuff[GET_PIXEL_B(j,i)];
        pixel_g = &framebuff[GET_PIXEL_G(j,i)];
        pixel_r = &framebuff[GET_PIXEL_R(j,i)];

        *pixel_b = 255-*pixel_b;
        *pixel_g = 255-*pixel_g;
        *pixel_r = 255-*pixel_r;
        }
    }

This successfully accessed the bytes in the array and changed the values (used to invert an image).

I wanted to create a structure containing the three pixel values, like so:

struct Pixel {
    char *pixel_b;
    char *pixel_g;
    char *pixel_r;
};

Then change the first bit of code to:

struct Pixel pixel;

    for (i=0;i<416;i++)
    {
        for (j=0;j<576;j++)
        {
        pixel.pixel_b = &framebuff[GET_PIXEL_B(j,i)];
        pixel.pixel_g = &framebuff[GET_PIXEL_G(j,i)];
        pixel.pixel_r = &framebuff[GET_PIXEL_R(j,i)];

        pixel.*pixel_b = 255-pixel.*pixel_b;
        pixel.*pixel_g = 255-pixel.*pixel_g;
        pixel.*pixel_r = 255-pixel.*pixel_r;
        }
    }

However it seems you can't just do this :P So after some more looking around I thought it may be best to change pixel to *pixel, and don't have pointers within it, however that didn't seem to work either. Is there a nice way to do what I'm trying to do? I haven't used structs in C in quite a while so I'm partially expecting I'm forgetting something very basic.

Any help would be greatly appreciated.

2 Answers 2

2

You have to dereference the struct.field, not just the field. The precedence for the . operator is higher than the * dereference operator, so no parenthesis are needed.

struct Pixel pixel;

for (i=0;i<416;i++)
{
    for (j=0;j<576;j++)
    {
    pixel.pixel_b = &framebuff[GET_PIXEL_B(j,i)];
    pixel.pixel_g = &framebuff[GET_PIXEL_G(j,i)];
    pixel.pixel_r = &framebuff[GET_PIXEL_R(j,i)];

    *pixel.pixel_b = 255 - *pixel.pixel_b;
    *pixel.pixel_g = 255 - *pixel.pixel_g;
    *pixel.pixel_r = 255 - *pixel.pixel_r;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can't believe I didn't try that, thought I had. Thanks a lot :) From running it first time it feels a little slower, although that could just be imaginary, would it in theory be any slower than the original method?
There is no reason in principle that it should be slower. The . dereference is handled at compile time. Of course, compilers can be silly sometimes.
0

It is the syntax. Switch the pixel.*pixel_b for *(pixel.pixel_b).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.