ANKIT MATHUR
ANKIT MATHUR

Reputation: 13

How to initialise nested structure variable?

struct date{
    int month;
    int day;
    int year;
};
struct employee{
    struct nmadtype nameaddr;
    int salary;
    struct date datehired;
};
struct employee e[3];
for(i=0;i<3;i++)
struct employee e[i].datehired={2,2,16};

i want to initialise employees date on which they hired through datehired variable but i dont want to initialise each member of struct date individually (like e[i].datehired.month=2)so i tried the last step but it is giving compilation error so plz suggest a method that will even work if my 3 employees have different hired date.

Upvotes: 0

Views: 47

Answers (2)

LPs
LPs

Reputation: 16213

You can use a struct date variable with init values to do so:

#include <stdio.h>

struct date{
     int month;
     int day;
     int year;
 };

 struct employee{
     struct date datehired;
 };

int main(void)
{
    struct employee e[3];
    struct date initVal= {2,2,16};

     for(size_t i=0;i<sizeof(e)/sizeof(e[0]);i++){
         e[i].datehired=initVal;
     }
}

Or using Compound Literals

#include <stdio.h>

struct date{
     int month;
     int day;
     int year;
 };

 struct employee{
     struct date datehired;
 };

int main(void)
{
    struct employee e[3];

     for(size_t i=0;i<sizeof(e)/sizeof(e[0]);i++){
         e[i].datehired=(struct date){2,2,16};;
     }
}

And the easiest and basic code is

#include <stdio.h>

struct date{
     int month;
     int day;
     int year;
 };

struct employee{
    struct date datehired;
};

int main(void)
{
    struct employee e[3];

     for(size_t i=0;i<sizeof(e)/sizeof(e[0]);i++)
     {
         e[i].datehired.month = 2;
         e[i].datehired.day   = 2;
         e[i].datehired.year  = 16;
     }
}

Upvotes: 0

dbush
dbush

Reputation: 223689

What you're attempting to do is an assignment, not an initialization, which is why it's failing. An initialization is done at the time a variable is defined.

What you can do is use a compound literal:

e[i].datehired = (struct date){2, 2, 16};

This creates a temporary variable of type struct date and assigns its values member-wise to the left side of the assignment.

Upvotes: 3

Related Questions