简体   繁体   English

在C中使用指针结构

[英]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. 但是,看来您不能仅仅这样做:P因此,在四处张望之后,我认为最好将pixel更改为* pixel,并且其中没有指针,但这似乎也不起作用。 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. 我已经有一段时间没有在C语言中使用过结构了,所以我部分地希望自己会忘记一些非常基本的东西。

Any help would be greatly appreciated. 任何帮助将不胜感激。

You have to dereference the struct.field, not just the field. 您必须取消引用struct.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) . pixel.*pixel_b*(pixel.pixel_b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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