如何在C语言中建立自己的数据结构
c语言提供了一些由系统已定义好的数据类型如int,float,char等,但只有这些类型还不能满足应用的要求,C语言中用户可以根据自己的需求建立自己的数据类型,并且用它来定义变量。
一、定义和使用结构体变量
1.我们可以简单的建立一个结构体,该结构体中包含学生的编号,姓名,年龄。2.在我们建立的结构体中还可以包含其他机构体。3.定义结构体变量有3种办法,这里只讲述最常用的俩种。
struct date
{ int mouth;
int day;}
struct student
{ int num;//定义学生的编号为整型
char name[20];//定义学生的名字为字符型
int age;//定义学生的年龄为整型
struct date festival;//定义节日为struct date数据类型
}student1={10101,"zhang",19};//定义结构体变量并对其进行初始化
struct student student2;//定义结构体变量student2
二、结构体数组
一个结构体中可以包含多个有关联的数据,但如果有n名学生那么我们就需要用到结构体数组。接下来我们通过一个例子来介绍结构体数组的使用方法。
简单的学生投票机制
有N个候选人,有n个选民。每个选民只能投票给一人,输入候选人的姓名来进行投票。
#include<stdio.h>
#include<string.h> //该头文件中有我们所需的strcmp函数
#define N 3 //候选人的数量
struct person
{
char name[20];
int count;
}; //声明结构体类型person
void main()
{
const int people=5; //参与投票的选民
struct person leader[N];
int i,n,max;char vote[20];
printf("请输入选票人的姓名");
for(i=0;i<N;i++)
{ gets(leader[i].name);
leader[i].count=0;
}
printf("开始投票,输入所支持的人姓名");
for(n=0;n<people;n++)
{ gets(vote);
for(i=0;i<3;i++) //利用循环和strcmp函数判断该票归属者
if(strcmp(leader[i].name,vote)==0)
leader[i].count++;
}
for(i=1,max=0;i<3;i++)
if(leader[max].count<leader[i].count)
max=i;
printf("最终选票最高的候选人是");
puts(leader[max].name);printf("\n");
printf("该候选人票数为%d\n",leader[max].count);
}
该投票机制比较简单,程序的代码复杂度是O(N*n)。
三、结构体指针
结构体指针就是指向该指向该结构体的指针,一个结构体变量的起始地址就是该结构体变量的指针。接下来我们将通过一个简单的代码来了解结构体指针。
学生信息的输入输出
有n个结构体变量,内含学生学号、姓名和三门课程的成绩。要求输出平均成绩最高的学生信息。(要求用函数化的思想来操作)。
#include<stdio.h>
#define N 3
struct student
{
int num;
char name[20];
float score[3];
float aver;
}; //定义每个学生的基本信息
void input(struct student stu[])
{
int k;
for(k=0;k<N;k++)
scanf("%d%s%f%f%f",&stu[k].num,stu[k].name,&stu[k].score[0],&stu[k].score[1],&stu[k].score[2]);
void aver(struct student stu[])
{
int k;
for(k=0;k<N;k++)
stu[k].aver=(stu[k].score[0]+stu[k].score[1]+stu[k].score[2])/3.0;
}
struct student max(struct student stu[]) //该函数是struct student类型,其返回值是一个结构体类型的数据
{
int max=0,i;
for(i=1;i<3;i++)
if(stu[max].aver<stu[i].aver)
max=i;
return(stu[max]); //返回平均成绩最大的学生信息
}
void print(struct student stu)
{
printf(" %d\n %s\n %3.1f\n %3.1f\n %3.1f\n %3.1f\n",stu.num,stu.name,stu.score[0],stu.score[1],stu.score[2],stu.aver);
}
void main()
{
struct student stu[N],*p=stu; //定义结构体数组和指向该结构数组的指针
input(p); //利用input函数输入每个学生信息
aver(p); //利用aver函数计算每个学生的平均成绩
print(max(stu)); //利用max函数找出最高平均成绩的学生然后用print函数输出学生信息
}
以上就是关于C语言结构体的一些基础知识。
第一次发博客,希望前辈们可以提出一些建议。努力进步!