Search code examples
csyntaxstructuremembers

How to reference a structure member through variable?


I am trying to cycle through the members of a structure using a For loop.

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

in Main, I would like to have

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

and be able to reference the members of struct Pixel as such...

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

instead of

pixels.Red;
pixels.Green;

I am getting a warning saying that it not allowed. I have tried parenthesis around the color[i], but to no avail.

Is this possible or am I just wasting my time?

If so, what syntax do I need to use?

Thanks


Solution

  • C just doesn't work this way. The best you could do is something like:

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