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实现允许把结构作为参数传递,或把指向结构的指针作为参数传递。
//如果只关心结构的一部分,还可以将结构成员作为参数传递給函数。