当前位置:网站首页>程序猿入门攻略(十一)——结构体
程序猿入门攻略(十一)——结构体
2022-06-30 06:28:00 【Yuan_o_】
1、结构体的声明
1.1 结构的基础知识
区分:
结构是一种集合。
数组十一组相同类型的集合。
C语言中的内置类型(char short int long float double…)只能表示单一的量,
而生活中经常有复杂对象需要我们去表示,如:
人:名字+电话+性别+身高
书:书名+作者+定价+书号
复杂对象的描述就会使用到:结构体
结构是一些值得集合,这些值成为成员变量。结构的每个成员可以是不同类型的变量。
1.2 结构的声明
例如描述一个人:
struct Peo
{
char name[20];//名字
char tele[12];//电话
char sex[5];//性别
int high;//身高
};
1.3 结构体成员的类型
结构体的成员可以是标量、数组、指针、甚至是其他结构体。
1.4 结构体变量的定义和初始化
补充:
打印方式及结果:
2、结构体成员的访问
#include <stdio.h>
struct Peo
{
char name[20];
char tele[12];
char sex[5];
int high;
};
struct St
{
struct Peo p;
int num;
float b;
};
void print1(struct Peo p)
{
printf("%s %s %s %d\n", p.name, p.tele, p.sex, p.high);//结构体指针.成员变量
}
void print2(struct Peo* sp)
{
printf("%s %s %s %d\n", sp->name,sp->tele,sp->sex,sp->high);//结构体变量->成员变量
}
int main()
{
struct Peo p1 = {
"张三","18888888888","男","188" };//结构体变量的创建
struct St s = {
{
"李四","16666666666","女","166"},100,3.14f };
printf("%s %s %s %d\n", p1.name, p1.tele, p1.sex, p1.high);
printf("%s %s %s %d %d %f\n", s.p.name, s.p.tele, s.p.sex, s.p.high, s.num, s.b);
print1(p1);//传结构体
print2(&p1);//传结构体地址
return 0;
}
3、结构体传参
- 在print1函数中,直接把结构体传参,形参是实参的一份临时拷贝,所以print1函数在内存中又开辟了一块和p1一样大的空间,并且要把p1中的内容传递过去,这样既浪费了空间,又浪费了时间。
- 在print2函数中,只是把结构体的地址传递过去,无非就是需要4/8个字节的空间来保存这个地址,大大节省了空间,时间。
总结:
函数传参的时候,函数是需要压栈的。
如果传递一个结构体对象的时候,结构体过大,函数压栈的系统开销比较大,所以会导致性能的下降。
所以,结构体传参的时候,要传结构体的地址。
边栏推荐
- HuaWei满级大牛首次分享出这份598页网络协议全彩手册
- VIM view file code
- ROS multi machine
- 判断h5在两端是在微信环境还是企业微信环境
- Win10 /11 开热点无法上网问题
- ES6 array traversal and Es5 array traversal
- 01. regular expression overview
- Usage of case, casez and casex statements in Verilog
- Installation and initialization of MariaDB database
- How does Altium designer hide some temporarily unnecessary classes, such as GND
猜你喜欢
1.9 - 存储器的分类
Px4 control mode summary
1.9 - Cache
gazebo/set_ model_ State topic driving UAV model through posture
DXP copper laying settings
从底层结构开始学习FPGA----RAM IP核及关键参数介绍
Installation and initialization of MariaDB database
One sentence introduction to Trojan horse
IO streams (common streams)
Idea run SQL file
随机推荐
Four ways to create multithreads
Wuenda coursera deep learning course
gazebo/set_ model_ State topic driving UAV model through posture
深度学习---三好学生各成绩所占权重问题(3)
Base64 explanation: playing with pictures Base64 encoding
Go pack and unpack
My experience in functional testing for so many years
[wechat applet: single or multiple styles, background color, rounded corners]
Px4 control mode summary
Why does the verification code not refresh when clicked
Beauty of Refactoring: when multithreaded batch processing task lifts the beam - Universal scaffold
Collections tool class (V)
关于Glide加载图片模糊不清楚
Common NPM install errors
RSA and AES
Variable parameters of go
Cocos studio3.1 installation package win
Several commands not commonly used in MySQL
旋转标注工具roLabelImg
Usage of case, casez and casex statements in Verilog