2016-12-26 143 views

回答

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; 

你声明了一个类型为的指针并给它的地址out.in1.in2。然后你可以直接使用它。

struct inner2 *in2ptr = &out.in1.in2; 
in2ptr->a = 1; 
in2ptr->b = 'x'; 
in2ptr->c = 3.14; 
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

你可以使用->操作。

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

+0

你能举个例子吗? –

0

不完全回答你的问题。

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-标准保证没有一个结构的第一个成员之前填充,它仍然不是很好。