重点:指针自加,指向下一个结构体数组单元
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #define max 10 5 #define min 3 6 7 typedef struct Stu{ 8 char * name; 9 int age; 10 int score; 11 } Stu; 12 13 //输入 14 void input(Stu *); 15 void output(Stu *); 16 void clean(Stu *); 17 18 void main(void) 19 { 20 Stu student[min]; 21 input(student); //相当于传入&student[0] 22 23 output(student); 24 clean(student); 25 } 26 27 void input(Stu * student) 28 { 29 char temp[20]; 30 int i=0; 31 puts("please input name"); 32 while(i<min & gets(temp) != NULL & temp[0] != ‘\0‘ ) 33 { 34 student->name = (char *) malloc(strlen(temp)+1); 35 strcpy(student->name,temp); 36 37 puts("age ?"); 38 scanf("%d",&student->age); 39 puts("score ?"); 40 scanf("%d",&student->score); 41 42 i++; 43 student++; //指针自加,指向下一个数组单元 44 45 while(getchar() != ‘\n‘) 46 continue; 47 48 if(i<min) 49 puts("next name"); 50 } 51 52 } 53 54 void output(Stu * student) 55 { 56 int i=0; 57 while(i<min){ 58 printf("%s---%d---%d\n",student->name,student->age,student->score); 59 i++; 60 student++; 61 } 62 63 } 64 65 void clean(Stu * student) 66 { 67 int i=0; 68 while(i<min){ 69 free(student->name); 70 i++; 71 student++; 72 } 73 }
时间: 2024-11-08 22:00:00