如何初始化嵌套结构变量? [英] 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想要通过datehired变量初始化雇员雇用的日期但我不想单独初始化结构日期的每个成员(如e [i] .datehired.month = 2)所以我尝试了最后一步,但它给出了编译错误,所以plz建议一种方法,即使我的3名员工也会工作有不同的雇用日期。
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.
推荐答案
试试这种方式:
Try this way:
const struct date DH = {2,2,16};
struct employee e[3];
int i;
for(i=0; i<3; i++)
e[i].datehired = DH;
第二行不正确:
The second line is incorrect:
for(i=0;i<3;i++)
struct employee e[i].datehired={2,2,16};
您不应在引用中指定 struct employee
元素。您还应该始终使用大括号来分隔循环,如下所示:
you should not specify struct employee
in the reference to your elements. You should also always use braces to delimit loops as below:
for(i=0;i<3;i++)
{
e[i].datehired={2,2,16};
}
普通的C不支持(扩展的初始化列表)(C ++ 11支持它)。
所以你必须设置每个成员,使用解决方案1中建议的其他结构,或使用辅助函数:
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);
这篇关于如何初始化嵌套结构变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!