Partial structure initialization?

Is it possible to statically initialize part of a structure?

I have:

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

When initializing and printing:

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

This will print an β€œicon” but not β€œ307”.

How can I make it use char name[20]and int bignoring it float a.

+4
source share
2 answers

You can use the initializers assigned by C99, as shown in @sps:

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

But in C89 there is no way to initialize only some members of the structure. So you will need to do:

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

Note even the designated initializers, other members that are explicitly initialized will be initialized to zero. Thus, both of the above equivalents.

(, 100 - ) .

+8

,

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

Source: https://habr.com/ru/post/1650291/


All Articles