![](/img/trans.png)
[英]C How can I acces struct members of a struct that is part of a struct array in another struct?
[英]How can I create an array with struct elements in C?
我想創建一個包含結構元素的數組,該結構的每個元素都是 boolean 並且在訪問每個數組元素時我想修改結構的值。 結構體是一個全局變量,修改數組元素的時候,我也想修改全局結構體。
typedef struct
{
bool bool1;
bool bool2;
bool bool2;
} struct_bool;
struct_bool my_struct;
bool array_dummy[3] = {my_struct.bool1, my_struct.bool2, my_struct.bool3};
array_dummy[0] = true;
array_dummy[1] = true;
array_dummy[2] = false;
使用指針:
bool *array_dummy[3] = { &my_struct.bool1, &my_struct.bool2, &my_struct.bool3 };
*array_dummy[0] = true;
*array_dummy[1] = true;
*array_dummy[2] = false;
我推薦的方法是使用匿名結構和聯合:
typedef struct {
union {
struct {
bool bool1;
bool bool2;
bool bool3;
};
bool booleans[3];
};
} struct_bool;
struct_bool my_struct;
這樣,您就可以將元素作為結構和數組來尋址。
my_struct.bool1 = true;
my_struct.booleans[1] = true;
my_struct.booleans[2] = false;
這要歸功於聯合元素共享其 memory 位置。 匿名結構和布爾數組都位於同一地址上,因此修改一個並讀取另一個將讀取該修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.