100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > C语言 结构体定义方法

C语言 结构体定义方法

时间:2018-09-03 04:10:10

相关推荐

C语言 结构体定义方法

结构声明(也见有称做定义一个结构体)是描述结构如何组合的主要方法。

一般形式是:

struct 结构名{

成员列表

};

struct关键词表示接下来是一个结构。

下面归纳几种定义结构体变量的方法。

第一种是最基本最标准的结构体定义,即先定义结构体类型,再定义结构体变量。

struct student{char no[20]; //学号char name[20]; //姓名char sex[5];//性别int age;//年龄};struct student stu1,stu2; //此时stu1,stu2为student结构体变量

后面再定义新的变量也是struct student做类型名,如 struct student stu3;

第二种定义结构体类型的同时定义结构体变量。

struct student{char no[20];//学号char name[20]; //姓名char sex[5];//性别int age;//年龄} stu1,stu2;

此后还可以继续定义student结构体变量,如:

struct student stu3;

第三种不指定结构体名而直接定义结构体变量。

struct{char no[20]; //学号char name[20];//姓名char sex[5];//性别int age;//年龄} stu1,stu2;

一般不使用这种方法,因为直接定义结构体变量stu1、stu2之后,就不能再继续定义该类型的变量。

没有typedef的方法都例举完了,后面都是带typedef的方法。

第四种先定义结构体类型,再定义结构体变量(有结构体名)。

typedef struct student{char no[20]; //学号char name[20]; //姓名char sex[5];//性别int age;//年龄}student_t;student_t stu1,stu2; //此时stu1,stu2为student结构体变量struct student stu3;

后面再定义新的变量用student_t 或 struct student 做类型名都可以。

student_t 是一个别名。

第五种先定义结构体类型,再定义结构体变量(无结构体名)。

typedef struct{char no[20]; //学号char name[20]; //姓名char sex[5];//性别int age;//年龄}student_t;student_t stu1,stu2; //此时stu1,stu2为student结构体变量

与第四种不同的是后面再定义新的变量只能用student_t 做类型名。

还有一种没有什么价值,相当于typedef白用了呗,效果与第一种方法无异。

typedef struct student{char no[20]; //学号char name[20]; //姓名char sex[5];//性别int age;//年龄};struct student stu1,stu2; //此时stu1,stu2为student结构体变量

实用情况中,第五种用得最多。

可以将下面这段 定义写在头文件中,供每个包含该头文件的源文件使用,定时变量的时候student_t stu1即可。

typedef struct{char no[20]; //学号char name[20]; //姓名char sex[5];//性别int age;//年龄}student_t;

也可以将下面这段 定义写在头文件中,供每个包含该头文件的源文件使用,定时变量的时候struct student stu1即可,大部分人可能会觉得student_t 比 struct student 看起来更加简便。

struct student{char no[20]; //学号char name[20]; //姓名char sex[5];//性别int age;//年龄};

参考鸣谢:

/please_fix_/article/details/104595440

https://yum9193./article/details/81190361

/p/521248221

/view/4ffde1d6f51fb7360b4c2e3f5727a5e9856a270f.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。