繁体   English   中英

访问嵌套结构中的成员

[英]Accessing a member in a nested structure

有没有一种方法可以访问嵌套在其他两个结构中的结构的各个成员,而无需多次使用点运算符?

有没有一种方法可以访问嵌套在其他两个结构中的结构的各个成员,而无需多次使用点运算符?

否。不通过标准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;
}

与某些with关键字的BASIC或Pascal变体不同,它允许您直接访问结构的内部成员,而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;

您可以使用->运算符。

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

没有完全回答您的问题。

可以通过获取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保证在结构的第一个成员之前没有填充。 仍然不是很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM