C-Void pointer inside a generic list (Contains stucture) -
i have 2 different stuctures need contain them in same generic list.
the structures :
typedef struct val1{ int num1; int num2; int num3; }val1; typedef struct val2{ char name[50]; char surname[50]; int id; }val2;
and list is:
typedef stuct list { void *value; struct node *next; }list; typedef struct l_head{ node *head; int num_members; }l_head;
i need use same list implementation list needs handle both of strucrure types.i cant figure out how initialize list , put elements in list .any advice helpfull.
the canonical solution c add common initial field having distinct values both structures.
typedef struct val1 { int discriminator; int num1; int num2; int num3; } val1; typedef struct val2 { int discriminator; char name[50]; char surname[50]; int id; } val2;
if neccessary, can define new struct instead.
has advantage of preserving previous layout , alignment guarantees:
struct packed { int discriminator; union {struct val1;struct val2}; };
anyway, integrate directly node:
typedef stuct node { struct node *next; int discriminator; /* might want reserve 0 no content */ union {struct val1;struct val2}; } node;
the technical term of solution "discriminated union".
Comments
Post a Comment