结构体的初始化

  结构体的初始化方式有多种,还有结构体数组的初始化,虽然好多平时用不到,但还是有必要了解一下。


1.结构体初始化

struct Student{

    int id;

    char name[10];

    int score;

};


定义一个结构体变量并初始化方法有:

  struct Student stu1 = {1, "Lily", 80};

  struct Student stu1 = {1};   //初始化个数少于结构体成员数时,只初始化前面的成员

  struct Student stu1 = {.id = 1};  //初始化某一特定成员


以上三种情况是声明并定义结构体进行初始化,如果先声明,后初始化,就需要进行强制类型转换。

如:

  struct Student stu1;

  stu1 = (struct Student){1, "Lily", 80};


2.结构体数组初始化

struct Student stu[2] = {

    {1, "Lily", 80},

    {2, “Tom", 70}

};


数组也可以初始化某一特定成员:

  struct Student stu[5] = {[0]={1,"Lily", 80}, [3]={3, "Jerry", 90}};

同样可以初始化它成员的特定成员:

  struct Student stu[5] = {[0].id=0};


如果先声明,后初始化则需要强制类型转化。

  struct Student stu[2];

  stu[1] = (struct Student){1, "Lily", 80};


(附加)3.嵌套结构体时,打印时要精确到最小单元

如:

struct birth{

    int month;

    int day;

};

struct Student {

    int num;

    struct birth birthday;

}; 

struct Student stu1 = {1, {12, 11}};

printf("%d %d %d",stu1.num, stu1.birthday.month, stu1.birthday.day);




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值