结构体
把有内在联系的变量组合即为结构体,结构体和数组的不同在于数组成员只能是同一类型的
定义结构体
struct student{
int name;
char sex;
int score;
}stu1,stu2,stu3;
或者
struct student{
....
};
student stu1,stu2,stu3;
使用结构体数组
三个候选人,每个选民投一票
#include#includestruct Person{
char name[20];
int count;
}leader[3]={"a",0,"b",0,"c",0};
int main()
{
int i,j;
char leaderName[20];
for(i=1;i<=10;i++)
{
scanf(“%s",leaderName);
for(j=0;j<3;j++)
{
if(strcmp(leaderName,leader[j].name)==0)
leader[j].count++;
}
printf("\nResult\n");
for(i=0;i<3;i++)
{
printf(%5s:%d\n",leader[i].name,leader[i].count);
}
return 0;
}
结构体指针
一个结构体变量的起始地址就是这个结构体变量的指针
指向结构体变量的指针必须和结构体变量的类型相同
struct Student *pt;
使用
struct Student stu_1;
struct Student *p;
p=&stu1;
printf("%s",stu_1.name);
printf("%s",(*p).name);
指向结构体数组的指针
struct Student stu[3]={...};
struct Student *p;
for(p=stu;pnum);
}
用指针处理链表
链表是一种常见的重要数据结构,可以动态底进行存储分析
建立简单的静态链表
#includestruct Student{
int num;
float score;
struct Student *next;
};
int main()
{
struct Student a,b,c,*head,*p;
a.num=1;a.score=1.1;
b.num=2;b.score=2.2;
c.num=3;c.score=3.3;
head=&a;
a.next=&b;
b.next=&c;
c.next=NULL;
p=head;
do{
printf("%ld %5.1f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
return 0;
}
建立动态链表
#include#include#define LEN sizeof(struct Student)
struct Student{
long num;
float score;
struct Student *next;
};
int n;
struct Student*creat(void)
{
struct Student*head;
struct Student *p1,*p2;
n=0;
p1=p2=(struct Student*)malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
n++;
if(n==1)head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct Student*)malloc(LEN);
scanf("%ld %f",&p1->num,&p1->score);
}
p2->next=NULL;
return (head);
}
输出链表
void print(struct Student *head)
{
struct Student *p;
p=head;
if(head!=NULL)
{
do{
printf("%lf %5.1f",p->num.p->score);
p=p->next;
}while(p!=NULL);
}
}