FletcherG FletcherG - 1 year ago 89
C Question

Partial initialization of struct?

Is it possible to statically initialise part of a struct?

The stuct I have:

struct data {
char name[20];
float a;
int b;
char c;

When initialsing and printing:

struct data badge = {"badge",307};
printf("%s,%d\n", badge.name, badge.b);

This will print out "badge", but not '307'.

How can I get this to use
char name[20]
int b
whilst ignoring
float a

Answer Source

You can use C99's designated initializers as suggested by @sps:

struct data badge = {.name = "badge", .b = 307};

But in C89, there's no way to initialise only certain members of a struct. So, you'd have to do:

struct data badge = {"badge", 0.0, 307, 0};

Notice even with designated initializers, other members which are explicitly initialized will be zero initialized. So, both of the above are equivalent.

But with designated initializers you don't have explicitly initialize it (imagine if you have struct with 100 members and you want to provide an initial for only 2 of them -- like in your example) and makes the code easier to read as well.