Here's initialization I just found in somebody else's question.
my_data data[]={ { .name = "Peter" }, { .name = "James" }, { .name = "John" }, { .name = "Mike" } };
I never saw something like this before and can't find explanation how is .name possible to be correct.
What I'm looking for is how step by step this process goes.
It looks like it gets:
data;
*data;
(*data).name;
(*data).name="Peter";
Or am I totally wrong?
Use List Notation to Initialize Array of Structs in C. Structures are derived data types that usually consist of multiple members. Note that the member declaration order in the struct definition matters, and when the initializer list is used, it follows the same order.
It's called designated initializer which is introduced in C99. It's used to initialize struct or arrays, in this example, struct . Show activity on this post. It's a designated initializer, introduced with the C99 standard; it allows you to initialize specific members of a struct or union object by name.
Initializing Array of Structures struct car { char make[20]; char model[30]; int year; }; struct car arr_car[2] = { {"Audi", "TT", 2016}, {"Bentley", "Azure", 2002} };
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With