C语言之结构体

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 //用指向函数的指针做函数参数
 4 #if(0)
 5 int main()
 6 {
 7     struct Student{
 8         long int num;
 9         char name[20];
10         char sex;
11         char addr[20];
12     }a={10101,"zhangsan",'M',"shandong"};
13     printf("%ld,%s,%c,%s",a.num,a.name,a.sex,a.addr);
14     return 0;
15 }
16 #endif
17 
18 #if(0)
19 //定义一个结构体
20 struct Student{
21     int num;
22     char name[20];
23     float score;
24 };
25 
26 int main()
27 {
28     //定义一个结构体数组,里面包含5个结构体变量
29     struct Student stu[5]={{10101,"zhang",66},{10102,"li",77},{10103,"zhao",32},
30                             {10104,"ke",69},{10105,"huang",100}};
31     struct Student temp;//定义一个结构体变量
32     const  int n=5;
33     int i,j,k;//定义变量
34     printf("the order is:\n");
35     for(i=0;i<n-1;i++){
36         k=i;
37         for(j=i+1;j<n;j++){
38             if(stu[j].score>stu[k].score){ //如果第1个学生的成绩大于第0个学生的成绩
39                 k=j;
40             }
41         temp=stu[k];
42         stu[k]=stu[i];
43         stu[i]=temp;//将结构体通过中间变量进行交换
44         }
45     }
46     for(i=0;i<n;i++){
47       printf("%6d,%8s,%6.2f\n",stu[i].num,stu[i].name,stu[i].score);
48     }
49     printf("\n");
50     return 0;
51 }
52 #endif
53 
54 #if(0)
55 int main(){
56     struct Student{
57         long int num;
58         char name[20];
59         char sex;
60         float score;
61     };
62     struct Student stu_1;
63     struct Student *p;//定义结构体指针
64     p=&stu_1;//将结构体变量的地址赋值给指针
65     stu_1.num=1001;
66     strcpy(stu_1.name,"huang");//此处是字符数组 指向第一个元素的地址 因此使用strcpy函数赋值
67     stu_1.sex='M';
68     stu_1.score=89.5;
69     printf("%ld,%s,%c,%.2f",(*p).num,(*p).name,(*p).sex,(*p).score);
70     return 0;
71 }
72 
73 #endif
74 
75 #if(1)
76 //定义一个结构体
77  struct Student{
78         int num;
79         char name[20];
80         char sex;
81         int age;
82     };
83 //定义一个结构体数组
84 struct Student stu[3]={{10011,"zhang",'M',20},{10012,"zhan",'M',20},{10013,"zha",'M',20}};
85 
86 
87 int main(){
88     //定义一个结构体指针
89     struct Student *p;
90     //利用for循环 指向结构体指针
91     for(p=stu;p<stu+3;p++){
92         printf("%d,%s,%c,%d\n",(*p).num,p->name,p->sex,p->age);
93     }
94     return 0;
95 }
96 #endif

 

posted @ 2020-03-13 15:35  萌萌~  阅读(200)  评论(0编辑  收藏  举报