C primier plus 結構和其他資料形式
阿新 • • 發佈:2018-12-08
14.18 程式設計練習.4
主要是是練習把結構傳遞給函式引數的兩種形式:傳遞結構整體本身;傳遞結構指標指向的成員值。
//向函式傳遞結構資訊,一是傳遞整個結構本身,二是利用結構指標傳遞結構成員。 #include<stdio.h> #include<string.h> #include<stdlib.h> #define MAX 40 struct info { char firstname[MAX]; char middlename[MAX]; char lastname[MAX]; }; struct member { char num[20];//用字元陣列儲存賬號,防止用int or double型會溢位資料。 struct info info_full;//結構巢狀。 }; void print(const struct member [],int);//使用結構陣列的函式。即傳遞給函式的是結構陣列!!! void print_p(char *,char *,char *,char *);//利用指標,傳遞結構的值。 int main(void) { struct member member_array[5]; int count=0; puts("Enter the infomation of person:"); puts("Enter the first name:"); while(count<5 && gets(member_array[count].info_full.firstname)!=NULL && member_array[count].info_full.firstname[0]!='\0') { puts("Enter the middle name:"); gets(member_array[count].info_full.middlename); puts("Enter the last name:"); gets(member_array[count].info_full.lastname); puts("Enter the social number:"); scanf("%s",&member_array[count].num); count++; while(getchar()!='\n') continue; if(count<5) puts("Enter the next first name:"); } puts("Print out by trans parameter:"); print(member_array,count); puts("Another print out by pointer toward value:"); for(int index=0;index<count;index++) print_p(member_array[index].info_full.firstname,member_array[index].info_full.middlename,member_array[index].info_full.lastname,member_array[index].num); return 0; } void print(const struct member member_array[],int count) { printf("Here is the list of infomation:\n"); for(int index=0;index<count;index++) if(member_array[index].info_full.middlename[0]=='\0') printf("%s %c %s -%s\n",member_array[index].info_full.firstname,member_array[index].info_full.middlename[0],member_array[index].info_full.lastname,member_array[index].num); else printf("%s %c. %s -%s\n",member_array[index].info_full.firstname,member_array[index].info_full.middlename[0],member_array[index].info_full.lastname,member_array[index].num); } void print_p(char *a,char *b,char *c,char *n) { if(b[0]=='\0') printf("%s %c %s -%s\n",a,' ',c,n); else printf("%s %c. %s -%s\n",a,b[0],c,n); } //C實現允許把結構作為引數傳遞,或把指向結構的指標作為引數傳遞。 //如果只關心結構的一部分,還可以將結構成員作為引數傳遞給函式。