如何通过变量引用结构成员?

时间:2014-10-22 23:09:14

标签: c syntax structure members

我试图使用For循环遍历结构的成员。

struct Pixel{
  unsigned char = Red, Green, Blue;
};

在Main,我想有

const char *color[]= {"Red", "Green", "Blue};

并且能够引用struct Pixel的成员......

struct Pixel pixels;
pixels.color[i]; // i being the counter in the For loop

而不是

pixels.Red;
pixels.Green;

我收到警告说不允许这样做。我试过围绕颜色[i]的括号,但无济于事。

这可能还是我只是在浪费时间?

如果是这样,我需要使用什么语法?

由于

1 个答案:

答案 0 :(得分:1)

C只是不这样做。你能做的最好就是:

struct Pixel {
    unsigned char Red;
    unsigned char Green;
    unsigned char Blue;
};

unsigned char get_element(struct Pixel * sp, const char * label)
{
    if ( !strcmp(label, "Red") ) {
        return sp->Red;
    }
    else if ( !strcmp(label, "Green") ) {
        return sp->Green;
    }
    else if ( !strcmp(label, "Blue") ) {
        return sp->Blue;
    }
    else {
        assert(false);
    }
}

int main(void)
{
    const char * color[] = {"Red", "Green", "Blue"};
    struct Pixel p = {255, 255, 255};
    for ( size_t i = 0; i < 3; ++i ) {
        unsigned char element = get_element(&p, color[i]);
        /*  do stuff  */
    }

    return 0;
}