结构体的初始化

来源:互联网 发布:日本农产品进出口数据 编辑:程序博客网 时间:2024/05/17 04:32

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


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 0