簡體   English   中英

指向不同結構的指針數組

[英]Array of pointers to different structs

可以做這樣的事情我如何初始化一個指向結構的指針數組? 但是有不同的結構?

例如

static struct structA_t a = {"ads", "as"};
static struct structB_t b = {"zzds", "dfr", "shywsd"};
static struct structC_t c = {"ssa", "ad", "dhksdhs"};

struct some_type *array[] = { &a, &b, &c};

some_type看起來如何?

您可以將some_type定義為聯合:

typedef union{
  struct structA_t;
  struct structB_t;
  struct structC_t;
}some_type;

這將導致您不知道數組中哪個元素實際包含什么的問題。

為了克服這個問題,添加另一個字段,指定要使用的內容:

/* numbers to identify the type of the valid some_type element */
typedef enum my_e_dataId{
  dataid_invalid = 0,
  dataid_a,
  dataid_b,
  dataid_c
} my_dataId;

typedef union u_data {
  struct structA_t* a;
  struct structB_t* b;
  struct structC_t* c;
}mydata;

typedef struct s_some_type{
  my_dataId dataId;
  mydata    myData;
}some_type;

然后,您可以按以下方式初始化數組:

some_type sta[] = {
  {dataid_a, (struct structA_t*) &a},
  {dataid_b, (struct structA_t*) &b},
  {dataid_c, (struct structA_t*) &c}
};

當您遍歷array的元素時,請首先評估dataId以便您了解myData包含的內容。 然后,例如,使用以下命令訪問第一個元素的數據

sta[0].myData.a->FIELDNAME_OF_A_TO_ACCESS

或第三個元素

sta[2].myData.c->FIELDNAME_OF_C_TO_ACCESS

有關工作示例,請參見此ideone: http ://ideone.com/fcjuR

在C語言中,可以使用void指針(用“ void”替換“ struct some_type”),但是您實際上不應該這樣做。 數組用於使用均質數據進行編程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM