访问嵌套结构中的成员

时间:2016-12-26 01:09:39

标签: c struct

有没有办法访问嵌套在其他两个结构中的结构的各个成员而不多次使用点运算符?

4 个答案:

答案 0 :(得分:2)

  

有没有办法访问嵌套在其他两个结构中的结构的各个成员而不多次使用点运算符?

没有。不是通过标准C。

为了使访问代码更清晰,您可能会考虑一些static inline辅助函数。

例如:

struct snap {
    int memb;
};

struct bar {
    struct snap sn;
};

struct foo {
    struct bar b;
}

static inline int foo_get_memb(const struct foo *f)
{
    return f->b.sn.memb;
}

答案 1 :(得分:2)

与BASIC或Pascal的某些变体不同,它们具有with关键字,允许您直接访问结构的内部成员,C没有这样的结构。

你可以用指针做到这一点。如果您有一个特定的内部成员,您将经常访问,您可以将该成员的地址存储在指针中,并通过指针访问该成员。

假设您有以下数据结构:

struct inner2 {
    int a;
    char b;
    float c;
};

struct inner1 {
    struct inner2 in2;
    int flag;
};

struct outer {
    struct inner1 in1;
    char *name;
};

外部类型的变量:

struct outer out;

而不是像这样访问最里面的struct的成员:

out.in1.in2.a = 1;
out.in1.in2.b = 'x';
out.in1.in2.c = 3.14;

您声明一个类型为struct inner2的指针,并为其指定out.in1.in2的地址。然后你可以直接使用它。

struct inner2 *in2ptr = &out.in1.in2;
in2ptr->a = 1;
in2ptr->b = 'x';
in2ptr->c = 3.14;

答案 2 :(得分:1)

您可以使用->运算符。

您可以获取内部成员的地址,然后通过指针访问它。

答案 3 :(得分:1)

没有完全回答你的问题。

可以通过struct的地址访问任何struct的第一个成员,将其转换为指向struct的指针类型第一个成员并取消引用它。

struct Foo
{
  int i;
  ...
};

struct Foo foo = {1};
int i = *((int*) &foo); /* Sets i to 1. */

将其与嵌套结构相匹配,例如:

struct Foo0
{
  struct Foo foo;
  ...
};

struct Foo1
{
  struct Foo0 foo0;
  ...
};

struct Foo2
{
  struct Foo1 foo1;
  ...
};

struct Foo2 foo2;
foo2.foo1.foo0.foo.i = 42;
int i = *((int*) &foo2); /* Initialises i to 42. */

struct Foo0 foo0 = {*((struct Foo*) &foo2)}; /* Initialises foo0 to f002.f001.foo0. */

这是明确定义的,因为C-Standard保证在struct的第一个成员之前没有填充。它还不好。

相关问题