【问题标题】:How to reference a structure member through variable?如何通过变量引用结构成员?
【发布时间】:2014-10-22 23:09:14
【问题描述】:

我正在尝试使用 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;

我收到一条警告说它不允许。我试过在 color[i] 周围加上括号,但无济于事。

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

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

谢谢

【问题讨论】:

  • struct Pixel{ unsigned char = Red, Green, Blue; }; 不是一个有效的结构声明,你能放一个最小的测试代码吗?
  • enum { Red, Green, Blue } color; - struct...{...color c;...};;这更多的是你想要做的吗?
  • 如果您想使用字符串引用变量或struct 元素,就像您可以使用 Python 之类的语言一样,您就是做不到,C 不能那样工作。您可以编写自己的逻辑来手动执行此操作,但这样做没有多大意义。
  • @JudgeHanger:这绝对不正确。

标签: c syntax structure members


【解决方案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;
}

【讨论】:

  • 它不会引用它,它会包含与它相同的值。如果你想要一个实际的引用,你可以写 get_element() 来返回一个指针。
猜你喜欢
  • 2022-12-17
  • 1970-01-01
  • 2016-07-15
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
相关资源
最近更新 更多