在网络协议、通信控制、嵌入式系统等我们需要传送的不是简单的字节流,而是包含了很多数据类型的一个整体。这时候,我们可以通过结构体来进行解决。
在结构体中,数据默认是共有的,可以进行直接的访问,而在类中,数据默认的是私有的。
结构体的定义如下:
- struct date
- {
- int year;
- int month;
- int day;
- };
也可以这样进行定义:
- struct date
- {
- int year;
- int month;
- int day;
- }Date;
当然也可以使用typedef进行定义
- typedef struct date
- {
- int year;
- int month;
- int day;
- }Date,*pDate;
而pDate = &Date;
结构体的定义本身是一条语句,所以要 以分号终止。
下面通过一个输出学生信息的程序来进行说明。
- #include<stdio.h>
- #include<string.h>
- void Print(struct Student*,int);
- struct Student
- {
- char name[20];
- char sex;
- char num[15];
- char Tel[12];
- };
- int main()
- {
- const int Size = 3;
- struct Student st[Size];
- Print(st,Size);
- return 0;
- }
- void Print(struct Student *pst,int size)
- {
- int i = 0;
- for(i =0;i< size; i++)
- {
- printf("请输入学生的姓名\n");
- scanf("%s",pst[i].name);
- printf("请输入学生性别M(男)F(女)\n");
- scanf("%s",&pst[i].sex);
- printf("请输入学生的学号\n");
- scanf("%s",&pst[i].num);
- printf("请输入学生的电话号码\n");
- scanf("%s",pst[i].Tel);
- }
- for(i = 0;i<size; i++)
- {
- printf("学生的姓名:%s\n",pst[i].name);
- printf("性别: %c\n",pst[i].sex);
- printf("学号: %s\n",pst[i].num);
- printf("电话: %s\n",pst[i].Tel);
- }
- }
程序的输出结果是
需要注意的是:
scanf("%s",pst[i].name);输入时不用取地址符,因为name本身就是一个地址。
再者,在程序传递参数使注意。void Print(struct Student*,int);注意两个参数的类型。