[英]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.