结构体

c语言如果需要不同类型的一个集合时,数组就不能用,这时候我们就会用结构体struct;

1.结构体的定义:

struct 结构体名

  {成员列表};

  结构体名,用作结构体类型的标志,它又称 结构体标记,大括号内是该结构体中的各个成员,由它们组成一个结构体,对各成员都应进行类型声明如:

  类型名 成员名;

定义的三种类型

1)先定义结构体类型,再定义结构体类型变量

struct stu 

{

char name[20];

int age ;

int source;

};

stuct  stu student1,student2;

2)定义结构体类型同时定义结构体变量

struct date

{

int year;

int month;

int day;

}time1,time2;

也可以定义如下变量;

struct date time1,time2;

3)直接定义结构体类型变量;

struct 

{

char name[20];

int age;

int source;

}person1,person2;

注意:该定义方法由于无法记录该结构体类型,所以除直接定义外,不能再定义该结构类型变量

3).嵌套定义问题:

struct date

{

int day;

int month;

int year;

};

struct stu

{

char name[20];

struct date birthday;/*出生年月,嵌套结构体类型*/

long num;

}person;

4)结构体数组定义及引用

struct stu

{

char name[20];

int age;

}student[20];/*定义结构体类型的数组*/

或者

struct stu student[20];

2.结构体的引用:

struct stu

{

char name[20];

int age;

}student[20];/*定义结构体类型的数组*/

引用:

student[0].name,student[0].age

 

posted @ 2017-11-05 22:04  梦醒青春时  阅读(205)  评论(0编辑  收藏  举报