I would like to initialize a NULL
terminated array of pointer to struct using compound literals.
Currently, I achieve this by:
struct object
{
int data1;
char data2;
};
struct object *object_array[] =
{
&(struct object) {1, 2},
&(struct object) {3, 4},
&(struct object) {5, 6},
&(struct object) {7, 8},
&(struct object) {9, 10},
NULL,
};
But, specifying (struct object)
is very verbose.
Is there a way to make my code look something like this:
struct object
{
int data1;
char data2;
};
struct object *object_array[] =
{
&{1, 2},
&{3, 4},
&{5, 6},
&{7, 8},
&{9, 10},
NULL,
};
You could use a temporary helper macro:
struct object
{
int data1;
char data2;
};
#define OB(data1, data2) &(struct object) {data1, data2}
struct object *object_array[] =
{
OB(1, 2),
OB(3, 4),
OB(5, 6),
OB(7, 8),
OB(9, 10),
NULL
};
#undef OB
This is just a more concise way to do what was done in first example.