当前位置:网站首页>C语言-结构体
C语言-结构体
2022-08-11 07:38:00 【天黑再醒】
目录
一.结构体类型的声明
结构是一些值的集合,这些值称为成员变量。结构的每个成员可以是不同类型的变量。结构的成员可以是标量、数组、指针,甚至是其他结构体。例如定义一名学生的信息:#include<stdio.h> typedef struct Stu //typedef可以省略,struct不能随便省略 { char name[20];//名字 int age;//年龄 char sex[5];//性别 char id[20];//学号 }Stu; //变量列表 int main() { struct Stu s1; struct Stu s2; Stu s3; return 0; }
二.结构体变量的定义和初始化
struct Point
{
int x;
int y;
}p1={21,14};//定义变量的同时赋初值.
struct X
{
char c;
struct Point p;
double d;
char arr[21];
};
int main ()
{
struct Point p={100,23};
struct X sx={ 'x',{12,23},3.14,"hello"};
return 0;
}
三.结构体成员的访问,结构体传参
结构变量的成员是通过点操作符(.)访问的。点操作符接受两个操作数。#include<stdio.h> struct Point { int x; int y; }p1={21,14}; struct X { char c; struct Point p; double d; char arr[21]; }; int main () { struct Point p={100,23}; struct X sx={ 'x',{12,23},3.14,"hello"}; printf("%c\n",sx.c); printf("%d %d\n",sx.p1.x,sx.p1.y); printf("%lf\n",sx.d); printf("%s\n",sx.arr); return 0; }
有时候我们得到的不是一个结构体变量,而是指向一个结构体的指针。#include<stdio.h> struct Point { int x; int y; }p1={21,14}; struct X { char c; struct Point p1; double d; char arr[21]; }; // void print1(struct X s) // { // printf("%c\n",s.c); // printf("%d %d\n",s.p1.x,s.p1.y); // printf("%lf\n",s.d); // printf("%s\n",s.arr); // } void print2(struct X* ps) { printf("%c\n",ps->c); printf("%d\n",ps->p1.x,ps->p1.y); printf("%lf\n",ps->d); printf("%s\n",ps->arr); } int main () { struct Point p={100,23}; struct X sx={ 'x',{12,23},3.14,"hello"}; //如果想修改信息 //sx.c='d'; //这样即可 // print1(sx); // 打印struct X类型的变量 print2(&sx); return 0; }
上面的 print1 和 print2 函数哪个好些?答案是:首选print2函数。原因:函数传参的时候,参数是需要压栈的。如果传递一个结构体对象的时候,结构体过大,参数压栈的的系统开销比较大,所以会导致性能的下降。结论:结构体传参的时候,要传结构体的地址。
边栏推荐
- Test cases are hard?Just have a hand
- Unity开发者必备的C#脚本技巧
- 囍楽云任务源码
- Tensorflow中使用tf.argmax返回张量沿指定维度最大值的索引
- 求职简历这样写,轻松搞定面试官
- 初级软件测试工程师笔试试题,你知道答案吗?
- Keep track of your monthly income and expenses through bookkeeping
- 流式结构化数据计算语言的进化与新选择
- About # SQL problem: how to set the following data by commas into multiple lines, in the form of column display
- 3.2-分类-Logistic回归
猜你喜欢
随机推荐
cdc连sqlserver异常对象可能有无法序列化的字段 有没有大佬看得懂的 帮忙解答一下
1046 punches (15 points)
1091 N-自守数 (15 分)
tf中矩阵乘法
【LeetCode】链表题解汇总
【TA-霜狼_may-《百人计划》】图形3.7.2 command buffer简
Mysql JSON对象和JSON数组查询
2021-08-11 for循环结合多线程异步查询并收集结果
Hibernate 的 Session 缓存相关操作
TF中的条件语句;where()
Kaldi语音识别工具编译问题记录(踩坑记录)
Keep track of your monthly income and expenses through bookkeeping
XXL-JOB 分布式任务调度中心搭建
Item 2 - Annual Income Judgment
查找最新人员工资和上上次人员工资的变动情况
Two startup methods and differences of Service
Do you know the basic process and use case design method of interface testing?
4.1ROS运行管理/launch文件
oracle19c不支持实时同步参数,请教一下大佬们有什么好的解决办法吗?
string类接口介绍及应用