当前位置:网站首页>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函数。原因:函数传参的时候,参数是需要压栈的。如果传递一个结构体对象的时候,结构体过大,参数压栈的的系统开销比较大,所以会导致性能的下降。结论:结构体传参的时候,要传结构体的地址。
边栏推荐
- 2021-08-11 for循环结合多线程异步查询并收集结果
- Tf中的平方,多次方,开方计算
- XXL-JOB 分布式任务调度中心搭建
- 1106 2019 Sequence (15 points)
- Evolution and New Choice of Streaming Structured Data Computing Language
- [Recommender System]: Overview of Collaborative Filtering and Content-Based Filtering
- excel 透视表 值显示内容 不显示计数
- 1.2-误差来源
- The easiest trick to support quick renaming of various files
- Square, multi-power, square root calculation in Tf
猜你喜欢
随机推荐
Activity的四种启动模式
求职简历这样写,轻松搞定面试官
1051 Multiplication of Complex Numbers (15 points)
1096 big beautiful numbers (15 points)
1101 How many times B is A (15 points)
查找最新人员工资和上上次人员工资的变动情况
1056 组合数的和 (15 分)
初级软件测试工程师笔试试题,你知道答案吗?
6月各手机银行活跃用户较快增长,创半年新高
leetcode:69. x 的平方根
动态代理学习
Four states of Activity
JRS303-数据校验
3.1-分类-概率生成模型
1036 跟奥巴马一起编程 (15 分)
3.2-分类-Logistic回归
Pico neo3 Unity打包设置
break pad源码编译--参考大佬博客的总结
Item 2 - Annual Income Judgment
The growth path of a 40W test engineer with an annual salary, which stage are you in?








