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" }
};
as:
my_data data[] = {
[0] = { .name = "Peter" },
[1] = { .name = "James" },
[2] = { .name = "John" },
[3] = { .name = "Mike" }
};
or:
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