失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 结构体变量和结构体指针变量作为函数参数传递问题

结构体变量和结构体指针变量作为函数参数传递问题

时间:2022-05-27 14:06:12

相关推荐

结构体变量和结构体指针变量作为函数参数传递问题

字符串赋值:strcpy_s(pstu->name, "张三");

需要引入头文件:#include <string.h>

#include <stdio.h>#include <string.h>struct Student {int age;char sex;char name[100];};void InputStudent(struct Student * pstu) { //pstu只占四个字节(*pstu).age = 10;strcpy_s(pstu->name, "张三");pstu->sex = 'F';}void OutStudent(struct Student ss) {printf("%d %c %s", ss.age, ss.sex, ss.name);}int main(void) {struct Student st;InputStudent(&st);printf("%d %c %s\n",st.age,st.sex,st.name);OutStudent(st);while (true){}}

代码分析;

void OutStudent(struct Student ss) {printf("%d %c %s", ss.age, ss.sex, ss.name);}

此处传递的是一个变量,此变量占的字节空间大,我们可以利用指针,指针只占四个字节空间,而且只存变量st的第一个字节地址,然而指针指向的是整个变量。因为指针前面的类型是struct Student代表的是整个变量

修改为指针后速度变快,占的内存空间也减小

#include <stdio.h>#include <string.h>struct Student {int age;char sex;char name[100];};void InputStudent(struct Student * pstu) { //pstu只占四个字节(*pstu).age = 10;strcpy_s(pstu->name, "张三");pstu->sex = 'F';}void OutStudent(struct Student * stu) {printf("%d %c %s", stu->age, stu->sex, stu->name);}int main(void) {struct Student st;InputStudent(&st);printf("%d %c %s\n",st.age,st.sex,st.name);OutStudent(&st);while (true){}}

当然眼睛是看不出来的,但是理论和事实就是这样的。

如果觉得《结构体变量和结构体指针变量作为函数参数传递问题》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。