#include<stdio.h>
#include<string.h>
struct Student
{
int age;
char sex;
char name[100];
};
void InputStudent(struct Student *pst)
{
pst->age = 10; //等同于 *pst.age = 10;
strcpy(pst->name,"张三");
pst->sex = 'F';
}
//void OutputStudent(struct Student st)
void OutputStudent(struct Student *st)
{
// printf("姓名:%s\n年龄:%d\n性别:%c\n",st.name,st.age,st.sex);
printf("姓名:%s\n年龄:%d\n性别:%c\n",(*st).name,(*st).age,(*st).sex);//这里*st要加上括号,这样连在一块写不加括号会报错
}
int main(void)
{
struct Student st;
InputStudent(&st); //这个必须发送地址,不然st的值不会被修改
//OutputStudent(st); //这样传参不好,它在OutputStudent函数做了一个st的副本,会消耗更多的内存.
OutputStudent(&st);//这样只做了一个st指针的副本,只占4个字节,比st副本少占内存容量,但发送地址,值有可能被修改的风险
return 0;
}
郝斌的C语言基础 159-161 通过函数完成对结构体变量的输入输出
最新推荐文章于 2025-05-06 13:07:41 发布