Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a struct with struct types inside

Tags:

c

struct

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;
like image 691
Tomzie Avatar asked Feb 25 '13 13:02

Tomzie


People also ask

How do you initialize a structure inside a structure?

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 ( = ).

How do you initialize a nested structure?

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.

How do you declare a struct in a struct?

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. */ };

Can we initialize inside a structure?

Structure members cannot be initialized with declaration.


2 Answers

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;
like image 88
md5 Avatar answered Oct 26 '22 21:10

md5


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};
like image 31
pmg Avatar answered Oct 26 '22 20:10

pmg