Click here to Skip to main content
15,888,340 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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};


What I have tried:

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.
Posted
Updated 17-Mar-17 4:34am

Try this way:
C
const struct date DH = {2,2,16};
struct employee e[3];
int i;

for(i=0; i<3; i++)
  e[i].datehired = DH;
 
Share this answer
 
The second line is incorrect:
C++
for(i=0;i<3;i++)
struct employee e[i].datehired={2,2,16};

you should not specify struct employee in the reference to your elements. You should also always use braces to delimit loops as below:
C++
for(i=0;i<3;i++)
{
    e[i].datehired={2,2,16};
}
 
Share this answer
 
Comments
CPallini 17-Mar-17 10:27am    
Hey Richard, as far as my gcc knows, that's an error.
Richard MacCutchan 17-Mar-17 12:33pm    
Works fine in MSVC (Visual Studio).
CPallini 17-Mar-17 12:51pm    
It possibly works with a C++ source file. I tried it (Visual Studio 2012) in a *.c source and got a syntax error.
Richard MacCutchan 17-Mar-17 12:55pm    
You are correct, of course. I was using VS 2013 and C++. But my comments still hold true.
CPallini 17-Mar-17 17:17pm    
Yes, that is valid C++ code. A classic example of C++ as 'better C'.
That (extended initializer lists) is not supported with plain C (it is supported with C++11).

So you have to set each member, use an additional struct as suggested in solution 1, or use a helper function:
void setEmployeeDate(struct employee *e, int day, int month, int year)
{
    e->datehired.day = day;
    e->datehired.month = month;
    e->datehired.year = year;
}

/* ... */
for(i=0; i<3; i++)
    setEmployeeDate(&e[i], 2, 2, 16);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900