【问题标题】:How do I access a pointer member inside a structure in C?如何访问 C 中结构内的指针成员?
【发布时间】:2014-03-03 08:05:00
【问题描述】:
struct sample
{
    int a;
    char b;
    float c;
    int *al;
    union un
    {
        int a;
        char c;
        float f;
    }*ptr;
}test;

如何访问结构成员 'al' 和联合成员 a、c、f?

【问题讨论】:

  • sample.ptr->你的作品?还是 *(sample.al)?
  • 我想在分别访问 al 和 a,c,f 时使用 'test' 和 'ptr'。它是如何工作的?
  • test.ptr->a; 会起作用。

标签: c pointers member member-pointers


【解决方案1】:

和别人没有区别:

  1. 访问al

    test.al
    

    如果您想要al 的值,可以通过*(test.al) 获得。

  2. 访问acf

    test.ptr->a;
    test.ptr->c;
    test.ptr->f;
    

【讨论】:

  • 仍然必须取消引用 test.al。 test->al 显然不起作用,因为你没有取消引用测试,所以 *(test.al) 会更清楚。
  • @ciphermagi test.al 是变量本身,*(test.al) 是该变量的值。无论如何,你说得有道理。答案已更新。
  • 我不相信*(test.al)*test.al 更清晰。
  • @JonathanLeffler 我想这取决于你对 C 运算符优先级的熟悉程度
【解决方案2】:

问题是你需要取消引用指针。

通常我们会这样做以取消对联合的引用。

test.*ptr.a.

这样做的问题是编译器将在解引用符号之前执行点符号,因此编译器将解引用联合中的字段,而不是它自己的联合。

为了解决这个问题,我们可以将'*ptr'放在括号中,以强制在访问该字段之前遵守联合。像这样。

test.(*ptr).a

为了更简单的语法,这也可以写成

test.ptr->a

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2010-11-22
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多