结构体变量.docVIP

  • 2
  • 0
  • 约7.14千字
  • 约 13页
  • 2017-12-22 发布于河南
  • 举报
结构体变量

结构体变量 struct Student //STRUCT不能省略 { int num; char name[20]; char sex; int age; float score; char addr[30]; }; //注意最后有一个分号 系统为结构体分配的内存为各成员类型所占内存之和 struct Student的内存=4+20+1+4+4+30=63 结构体类型的一般形式 struct 结构体名(域表)(形如Student) { 成员表列 //成员必须进行类型声明 }; 成员可以属于另外一个结构体类型,例 struct Date { int month; int day; int year; }; struct Student { int num; char sex; char addr[30]; int age; struct Date birthday; //结构体类型也可以像普通结构类型一样使用 char name[20]; }; 声明类型的同时定义变量 struct Student { int num; char name[20]; char sex; int age; float score; char addr[30]; }student1,student2; 结构体变量的初始化 #includestdio.h int main() { struct Student { int num; char name[20]; char sex; char addr[30]; }a={10010,lilin,M,123 Biejing Road}; printf(No.:%d\nname:%s\nsex:%c\naddr:%s\n,a.num,a.name,a.sex,a.addr); return 0; } 结构体变量中成员的值的引用 结构体变量.成员名 #includestdio.h int main() { struct Student { int num; char name[20]; float score; }student1,student2; scanf(%d%s%f,student1.num,student1.name,student1.score); //数组本身就代表地址,所以输入时不用加地址符 scanf(%d%s%f,student2.num,student2.name,student2.score); printf(the higher score is:\n); if(student1.scorestudent2.score) printf(%d %s %6.2f\n,student1.num,student1.name,student1.score); else if(student1.scorestudent2.score) printf(%d %s %6.2\nf,student2.num,student2.name,student2.score); else { printf(%d %s %6.2f\n,student1.num,student1.name,student1.score); printf(%d %s %6.2f\n,student2.num,student2.name,student2.score); } return 0; } 使用结构体数组 1)定义结构体数组 投票程序 #includestring.h #includestdio.h struct Person {char name[20]; int count; }leader[3]={li,0,zhang,0,wang,0}; int main() {int i,j; char leader_name[20]; for(i=1;i=10;i++) {scanf(%s,leader_name); for(j=0;j3;j++) if(strcmp(leader_name,leader[j].name)==0)leader[j].count++; } printf(\nresult:\n); for(i=0;i3;i++) printf(%5s:%d\n,leader[i].name,leader[i].count); return 0; } 如何定义一个结构体数组 [1]struct 结构体名 {成员列表}数组名[数组长度]; [2]先声明一个结构体类型(如),然后再用此类型定义结构体数组: 结构体类型 数组名[数组长度]; like :struct Person leader[3]; st

文档评论(0)

1亿VIP精品文档

相关文档