I would like to create a struct Person, which consists of two struct types and a variable inside. How can I initialize and use the struct Person then?
struct name{
char *firstName;
char *lastName;
} name;
struct address{
char *street;
int number;
} address;
struct person{
struct name fullName;
struct address fullAddress;
int age;
} person;
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
struct dateOfBirth dob={15,10,1990}; struct studentDetails std={"Mike",21,dob}; Initialize the first structure first, then use structure variable in the initialization statement of main (parent) structure.
The general syntax for a struct declaration in C is: struct tag_name { type member1; type member2; /* declare as many members as desired, but the entire structure size must be known to the compiler. */ };
Structure members cannot be initialized with declaration.
You can use nested {}
.
struct person
{
struct name fullName;
struct address fullAddress;
int age;
} person =
{
{
"First Name", /* person.fullName.firstName */
"Last Name", /* person.fullName.lastName */
},
{
"Street", /* person.fullAddress.street */
42 /* person.fullAddress.number */
},
42 /* person.age */
};
Then you can access to the other members as follow:
person.fullName.firstName;
person.fullName.lastName;
person.fullAddress.street;
person.fullAddress.number;
person.age;
For a 18-year-old John Doe, living at address, 42
struct person{
struct name fullName;
struct address fullAddress;
int age;
} person = {{"John", "Doe"}, {"address", 42}, 18};
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