It is possible to do something like this How can I initialize an array of pointers to structs? but with different structs?
Eg
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};
How some_type will look like?
You could define some_type
as a union:
typedef union{
struct structA_t;
struct structB_t;
struct structC_t;
}some_type;
This will lead you to the problem that you don't know what's actually contained in which element in the array.
To overcome this, add another field specifying the content that is used:
/* 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;
Then you could initialize your array as follows:
some_type sta[] = {
{dataid_a, (struct structA_t*) &a},
{dataid_b, (struct structA_t*) &b},
{dataid_c, (struct structA_t*) &c}
};
When you loop over the elements of array
, first evaluate dataId
so that you know what's contained in myData
. Then, for example, access the data of the first element using
sta[0].myData.a->FIELDNAME_OF_A_TO_ACCESS
or the third element with
sta[2].myData.c->FIELDNAME_OF_C_TO_ACCESS
See this ideone for a working example: http://ideone.com/fcjuR
In C this is possible with void pointers (Replace "struct some_type" with "void"), but you really shouldn't be doing this. Arrays are for programming with homogeneous data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.