2016-12-26 142 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-標準保證沒有一個結構的第一個成員之前填充,它仍然不是很好。