结构体变量和结构体指针变量作为函数参数传递问题
生活随笔
收集整理的這篇文章主要介紹了
结构体变量和结构体指针变量作为函数参数传递问题
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?字符串賦值: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只占四個(gè)字節(jié)(*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); }此處傳遞的是一個(gè)變量,此變量占的字節(jié)空間大,我們可以利用指針,指針只占四個(gè)字節(jié)空間,而且只存變量st的第一個(gè)字節(jié)地址,然而指針指向的是整個(gè)變量。因?yàn)橹羔樓懊娴念愋褪莝truct Student代表的是整個(gè)變量
修改為指針后速度變快,占的內(nèi)存空間也減小
#include <stdio.h> #include <string.h>struct Student {int age;char sex;char name[100]; };void InputStudent(struct Student * pstu) { //pstu只占四個(gè)字節(jié)(*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){} }當(dāng)然眼睛是看不出來的,但是理論和事實(shí)就是這樣的。
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的结构体变量和结构体指针变量作为函数参数传递问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言再学习 -- 循环语句
- 下一篇: C语言再学习 -- ctype.h字符判