简体   繁体   中英

Accessing a member in a nested structure

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

Is there a way to access individual members of a structure that is nested inside two other structures without using the dot operator multiple times?

No. Not via standard C.

To make the accessing code cleaner however, you might consider some static inline helper functions.

For example:

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;
}

Unlike some variants of BASIC or Pascal that have a with keyword which allows you to access inner members of a structure directly, C has no such construct.

You can do this however with pointers. If you have a particular inner member you're going to access frequently, you can store the address of that member in a pointer and access the member through the pointer.

Suppose for example you had the following data structures:

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

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

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

And a variable of the outer type:

struct outer out;

Instead of accessing the members of the innermost struct like this:

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

You declare a pointer of type struct inner2 and give it the address of out.in1.in2 . Then you can work directly with that.

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

You could use the -> operator.

You could take the address of an inner member and then access it via the pointer.

Not completely answering your question.

The 1st member of any struct can be accessed by taking the struct 's address, casting it to a pointer type pointing to the struct 's 1st member and dereferencing it.

struct Foo
{
  int i;
  ...
};

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

Adapting this to nested struct's gives us for example:

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. */

This is well defined, as the C-Standard guarantees that there is no padding before a struct's 1st member. Still it's not nice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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