c语言结构体基础,C语言 结构体基础

结构体

把有内在联系的变量组合即为结构体,结构体和数组的不同在于数组成员只能是同一类型的

定义结构体

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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值