Issue
This is how I can initialize a struct with pointers at build time.
struct example_struct {
int count;
int *values;
};
int i1[] = { 1, 2 };
int i2[] = { 10, 20, 30 };
struct example_struct items[] = {
{ .count = 2, .values = &i1[0] },
{ .count = 3, .values = &i2[0] },
{ .count = 0, .values = NULL },
};
The actual situation I am facing is quite lengthy and more complex than this example.
Therefore I am looking for a way to circumvent extra declaration of the arrays. Instead I would like to directly note the arrays in place,
that means convert .values = &i1[0]
into something like .values = { 1, 2 }
(which unfortunately is invalid syntax for gcc).
Does a solution exist for this?
To be clear, I know this example could be changed to
items[] = {
2, 1, 2,
3, 10, 20, 30
};
and reading values in a different way. But my case really requires pointers to elements that normally are read at runtime from variable configurations.
Solution
You can use compound literals. Research the lifetime of compound literals to make sure they will be valid upon use.
.values = (int[]){1, 2}
Maybe I am thinking ahead of myself, but your code example could look like:
#define ITEM(...) { \
.count = sizeof((int[]){__VA_ARGS__})/sizeof(int), \
.values = (int[]){__VA_ARGS__}, \
}
struct example_struct items[] = {
ITEM(1, 2),
ITEM(10, 20, 30),
{0},
};
Answered By - KamilCuk Answer Checked By - Mary Flores (WPSolving Volunteer)