1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include<stdio.h> #include<string.h>
struct namect{
char fname[20]; char lname[20]; int letters; };
struct namect getinfo(void); struct namect makeinfo(struct namect); void showinfo(struct namect);
int main(void) { struct namect person; person=getinfo(); person=makeinfo(person); showinfo(person); return 0; }
struct namect getinfo(void) { struct namect temp; printf("please enter you first name.\n"); gets(temp.fname); printf("please enter you last name.\n"); gets(temp.lname); return temp; }
struct namect makeinfo(struct namect info) { info.letters=strlen(info.fname)+strlen(info.lname); return info;
} void showinfo (struct namect info) { printf("%s %s ,your name contains %d letters .\n",info.fname,info.lname,info.letters);
}
程序的运行结果图如下: [正确的改变了letters的值](http:
情形2: 如果将person=makeinfo(person)改为makeinfo(person),则运行结果如下: [letters得到一个随机的值](http:
3.结构体指针作为参数 将结构体指针作为函数的参数,从而直接去改变letters的值,相关代码如下:
#include<stdio.h> #include<string.h>
struct namect{
char fname[20]; char lname[20]; int letters; };
struct namect getinfo(void); void makeinfo(struct namect *pst); void showinfo(struct namect);
int main(void) { struct namect person; person=getinfo(); makeinfo(&person); showinfo(person); 、、 return 0; }
struct namect getinfo(void) { struct namect temp; printf("please enter you first name.\n"); gets(temp.fname); printf("please enter you last name.\n"); gets(temp.lname); return temp; }
void makeinfo(struct namect *pst) { pst->letters=strlen(pst->fname)+strlen(pst->lname);
} void showinfo (struct namect info) { printf("%s %s ,your name contains %d letters .\n",info.fname,info.lname,info.letters);
}
|