当前位置:网站首页>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函数。原因:函数传参的时候,参数是需要压栈的。如果传递一个结构体对象的时候,结构体过大,参数压栈的的系统开销比较大,所以会导致性能的下降。结论:结构体传参的时候,要传结构体的地址。
边栏推荐
- 基于微信小程序的租房小程序
- 美术2.4 UV原理基础
- oracle19c不支持实时同步参数,请教一下大佬们有什么好的解决办法吗?
- 动态代理学习
- Pico neo3 Unity打包设置
- Redis source code: how to view the Redis source code, the order of viewing the Redis source code, the sequence of the source code from the external data structure of Redis to the internal data structu
- Redis source code-String: Redis String command, Redis String storage principle, three encoding types of Redis string, Redis String SDS source code analysis, Redis String application scenarios
- TF中使用softmax函数;
- 流式结构化数据计算语言的进化与新选择
- 1056 Sum of Combinations (15 points)
猜你喜欢
随机推荐
Do you know the basic process and use case design method of interface testing?
Activity的四种状态
【BM87 合并两个有序的数组】
CIKM 2022 AnalytiCup Competition: Federal Heterogeneous Task Learning
tf.reduce_mean()与tf.reduce_sum()
2.1 - Gradient Descent
测试用例很难?有手就行
3.1-Classification-probabilistic generative model
AcWing 272. 最长公共上升子序列
为什么会没有内存了呢
About # SQL problem: how to set the following data by commas into multiple lines, in the form of column display
少年成就黑客,需要这些技能
Evolution and New Choice of Streaming Structured Data Computing Language
matplotlib
1051 复数乘法 (15 分)
【Day_13 0509】▲跳石板
6月各手机银行活跃用户较快增长,创半年新高
1051 Multiplication of Complex Numbers (15 points)
tf中矩阵乘法
excel 透视表 值显示内容 不显示计数