2

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

elpablo
  • 51
  • 1
  • 4
  • 11
  • 3
    `struct Pixel{ unsigned char = Red, Green, Blue; };` is not a valid structure declaration, could you put your a minimal test code? – ouah Oct 22 '14 at 23:22
  • `enum { Red, Green, Blue } color;` - `struct...{...color c;...};`; is that more of what you're trying to do? – ChiefTwoPencils Oct 22 '14 at 23:24
  • If you want to refer to variables or `struct` elements using strings, like you might be able to in a language like Python, you just can't, C doesn't work that way. You could write your own logic to do that manually, but it wouldn't make a lot of sense to do so. – Crowman Oct 22 '14 at 23:25
  • @JudgeHanger: It's definitely not correct. – Crowman Oct 22 '14 at 23:32
  • Possible duplicate of [access struct member using a user variable](https://stackoverflow.com/questions/16649660/access-struct-member-using-a-user-variable) – y.luis.rojo Nov 06 '18 at 10:47

1 Answers1

2

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;
}
Crowman
  • 25,242
  • 5
  • 48
  • 56
  • It wouldn't reference it, it would contain the same value as it. You could write `get_element()` to return a pointer if you wanted an actual reference instead. – Crowman Oct 22 '14 at 23:37