结构体定义
C语言允许用户自己建立由不同类型数据组成的组合型的数据结构,它称之为结构体。
声明一个结构体类型的一般形式为:
struct 结构体名
{成员表列};
具体的使用方法如下:
struct Student
{
int num;
char name[20];
char sex;
int age;
float score;
char addr[30];
};
定义结构体变量
上述只是建立了一个结构体类型,它相当于一个模型,并没有定义变量,其中并无具体的数据,系统也并不对它分配存储空间。对于结构体的定义,有如下三种方案:
先声明结构体类型,再定义该类型的变量
struct Student student1,student2;
在声明类型的时候同时定义变量
struct Student
{
int num;
char name[20];
int age;
}student1,student2;
这种定义的一般形式为
struct 结构体名
{
成员列表
}变量名表列;
不指定类型名而直接定义结构体类型变量
其一般形式为
struct
{
成员表列
}变量名表列;
上述指定了一个无名的结构体类型,它没有名字,所以也就不能再以此结构体类型去定义其他变量。
定义结构体数组
下面代码展示了结构体数组的使用:
#include <string.h>
#include <stdio.h>
struct Person
{
char name[20];
int count;
}leader[3] = {"Li",0,"zhang",0,"sun",0};
int main()
{
int i,j;
char leader_name[20];
for(i=1;i<=5;i++)
{
scanf("%s",leader_name);
for(j=0;j<3;j++)
{
if(strcmp(leader_name,leader[j].name)==0)
leader[j].count++;
}
}
printf("result:\n");
for(i=0;i<3;i++)
{
printf("%5s:%d\n",leader[i].name,leader[i].count);
}
return 0;
}
定义结构体数组的一般形式
(1)struct 结构体名
{
成员表列
}数组名[数组长度];
(2)先声明一个结构体类型,然后再用此类型定义结构体数组
如:
struct Person leader[3];
结构体指针
指向结构体变量的指针
指向结构体对象的指针变量既可以指向结构体变量,也可以指向结构体数组中的元素。指针变量的类型必须与结构体体变量的类型相同。
比如定义指针变量的时候,这样定义
struct student *pt;//pt可以指向struct student 类型的变量或者数组元素
具体的例子如下:
#include <stdio.h>
#include <string.h>
int main()
{
struct Student
{
long num;
char name[20];
char sex;
float score;
};
struct Student stu_1;
struct Student *p;
p = &stu_1;
stu_1.num = 10101;
strcpy(stu_1.name,"Li Lin");
stu_1.sex = 'M';
stu_1.score = 89.5;
printf("NO.%1d",(*p).num);
return 0;
}
typedf的用法
命名一个新的类型名代表结构体类型:
typedf struct
{
int month;
int day;
int year;
}Date;
//定义变量
Date birthday;
Date *p;