通过函数完成对结构体变量的输入和输出

 1 /*结构体变量和结构体指针变量作为函数参数传递的问题
 2    通过函数完成对结构体变量的输入和输出。
 3 */
 4 
 5 # include <stdio.h>
 6 # include <string.h>
 7 
 8 
 9 struct Student 
10 {
11     int age;
12     char sex;
13     char name[100];
14 };     //分号不能少
15 
16 void InputStudent(struct Student *);
17 void OutputStudent(struct Student ss);
18 
19 
20 int main(void)
21 {
22     struct Student st;
23 
24     InputStudent(&st);//对结构体变量输入,必须发送st的地址
25     OutputStudent(st);//对结构体变量输出,可以发送st的地址,也可以发送st的内容
26 
27     return 0;
28 }
29 
30 void OutputStudent(struct Student ss)
31 {
32         printf("age = %d, sex = %c, name = %s\n", ss.age, ss.sex, ss.name);
33 }
34 
35 void InputStudent(struct Student *pstu)  //pstu只占四个字节。
36 {
37     (*pstu).age = 10;
38     strcpy(pstu ->name, "张三");
39     pstu ->sex = 'F';
40     
41 }
42 /*
43 在Vc++6.0中显示的结果是:
44 =================================================
45 age = 10, sex = F, name = 张三
46 =================================================
47 
48 */
49 
50 /*
51 本函数无法修改主函数st的值,所以本函数是错误的。
52 void InputStudent(struct Student stu)
53 {
54     stu.age = 10;
55     strcpy(stu.name, "张三");//不能写成stu.name = "张三";
56     stu.sex = 'f';
57     
58 
59 }
60 */

posted on 2012-09-05 22:47  Your Song  阅读(3288)  评论(1编辑  收藏  举报

导航