简体   繁体   中英

Using a struct of pointers in C

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.

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;
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM