Initializing array of structures [duplicate]

my_data is a struct with name as a field and data[] is arry of structs, you are initializing each index. read following:

5.20 Designated Initializers:

In a structure initializer, specify the name of a field to initialize with .fieldname =' before the element value. For example, given the following structure,

struct point < int x, y; >; 

the following initialization

struct point p = < .y = yvalue, .x = xvalue >; 

is equivalent to

struct point p = < xvalue, yvalue >; 

Another syntax which has the same meaning, obsolete since GCC 2.5, is fieldname:' , as shown here:

struct point p = < y: yvalue, x: xvalue >; 

You can also write:

my_data data[] = < < .name = "Peter" >, < .name = "James" >, < .name = "John" >, < .name = "Mike" >>; 
my_data data[] = < [0] = < .name = "Peter" >, [1] = < .name = "James" >, [2] = < .name = "John" >, [3] = < .name = "Mike" >>; 
my_data data[] = < [0].name = "Peter", [1].name = "James", [2].name = "John", [3].name = "Mike" >; 

Second and third forms may be convenient as you don't need to write in order for example all of the above example are equivalent to:

my_data data[] = < [3].name = "Mike", [1].name = "James", [0].name = "Peter", [2].name = "John" >; 

If you have multiple fields in your struct (for example, an int age ), you can initialize all of them at once using the following:

my_data data[] = < [3].name = "Mike", [2].age = 40, [1].name = "James", [3].age = 23, [0].name = "Peter", [2].name = "John" >; 

To understand array initialization read Strange initializer expression?

Additionally, you may also like to read @Shafik Yaghmour's answer for switch case: What is “…” in switch-case in C code

9,097 5 5 gold badges 31 31 silver badges 48 48 bronze badges answered Sep 20, 2013 at 16:36 Grijesh Chauhan Grijesh Chauhan 58k 20 20 gold badges 142 142 silver badges 213 213 bronze badges

There's no "step-by-step" here. When initialization is performed with constant expressions, the process is essentially performed at compile time. Of course, if the array is declared as a local object, it is allocated locally and initialized at run-time, but that can be still thought of as a single-step process that cannot be meaningfully subdivided.

Designated initializers allow you to supply an initializer for a specific member of struct object (or a specific element of an array). All other members get zero-initialized. So, if my_data is declared as

typedef struct my_data < int a; const char *name; double x; >my_data; 
my_data data[]=< < .name = "Peter" >, < .name = "James" >, < .name = "John" >, < .name = "Mike" >>; 

is simply a more compact form of

my_data data[4]=< < 0, "Peter", 0 >, < 0, "James", 0 >, < 0, "John", 0 >, < 0, "Mike", 0 >>; 

I hope you know what the latter does.