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

本文详细解析了C语言中结构体变量及结构体指针作为函数参数的使用方法,阐述了如何通过函数实现结构体变量的输入与输出,强调了地址传递的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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 */

转载于:https://www.cnblogs.com/jssong20000/archive/2012/09/05/2672648.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值