当前位置:网站首页>Introduction to C language custom types (structure, enumeration, union, bit segment)
Introduction to C language custom types (structure, enumeration, union, bit segment)
2022-06-24 04:23:00 【InfoQ】
1. Structure
1.1 Structure overview
1.1.1 Structure concept
1.1.2 Declaration and use of structures
// Structure
struct Stu
{
char name[20];// full name
char sex[5];// Gender
char id[20];// Student number
int age;// Age
double grade;// achievement
}student;
struct Stu Structural members student// Anonymous struct type
struct
{
int a;
char b;
float c;
}x;
struct
{
int a;
char b;
float c;
}a[20], *p;
pxpstruct Node
{
int data;
struct Node next;
};
struct Node
{
int data;
struct Node* next;
};
typedeftypedef// The wrong sample :
typedef struct NODE
{
int data;
Node* next;
}Node;
// The correct sample :
typedef struct NODE
{
int data;
struct NODE* next;
}Node;
#include <stdio.h>
int main()
{
struct Stu s = { " Zhang San "," male ","20210618",20,99 };// Structure declaration and initialization
printf(" full name :%s\n", s.name);// Structure member access method 1: Structure variable name . Structure member name
printf(" Gender :%s\n", s.sex);
struct Stu* ps = &s;
printf(" Student number :%s\n", ps->id);// Structure access member mode 2: Structure pointer -> Structure member name
printf(" Age :%d\n", ps->age);
printf("C Language test results :%.2lf\n", ps->grade);
return 0;
}
full name : Zhang San
Gender : male
Student number :20210618
Age :20
C Language test results :99.00
D:\gtee\C-learning-code-and-project\test_922\Debug\test_922.exe ( process 26272) Exited , The code is 0.
Press any key to close this window . . .
1.2 Structure alignment and its size calculation
1.2.1 Offset

1.2.2 Calculation of structure size
81#pragma pack(4)// Set the default alignment number to 4
#pragma pack()// No parameter means the default value is 8(vs compiler )
- Platform reasons ( Reasons for transplantation ): Not all hardware platforms can access any data on any address ; Some hardware platforms can only access certain types of data at certain addresses , Otherwise, a hardware exception will be thrown .
- Performance reasons :data structure ( Especially stacks ) It should be aligned as far as possible on the natural boundary . The reason is to access misaligned memory , The processor needs to make two memory accesses ; The aligned memory access only needs one access .
- [ ] The offset between the first member of the structure and the structure is
0.
- [ ] Structure members need to be aligned to an integer multiple of the alignment number ( Offset ) It's about .
- [ ] Each structure member has an alignment number , The alignment number is the smaller of the compiler default value and the structure member size .
- [ ] The total size of the structure is the maximum number of alignments ( The largest alignment number of each member of the structure ) Integer multiple .
- [ ] If there is a nested structure in the structure , The nested structure is aligned to an integral multiple of its maximum alignment , The overall size of the structure is the maximum number of alignments ( The number of alignments with nested structures ) Integer multiple .
// practice 1
struct S1
{
char c1;
int i;
char c2;
};
// practice 2
struct S2
{
char c1;
char c2;
int i;
};
// practice 3
struct S3
{
double d;
char c;
int i;
};
// practice 4- Structure nesting problem
struct S4
{
char c1;
struct S3 s3;
double d;
};
char c1101
int i444
char c21181c28
c294412charc1c2111c2c1424488
double88char19int44121616
S3816char11S3168S38824double88243232
int main()
{
printf("%d\n", sizeof(struct S1));
printf("%d\n", sizeof(struct S2));
printf("%d\n", sizeof(struct S3));
printf("%d\n", sizeof(struct S4));
return 0;
}
12
8
16
32
D:\gtee\C-learning-code-and-project\test_922\Debug\test_922.exe ( process 34308) Exited , The code is 0.
Press any key to close this window . . .
1.3 Structure and bit segment
1.3.1 Bit segment
1.3.2 Bit segment implementation structure
struct A {
int _a:2;
int _b:5;
int _c:10;
int _d:30;
};
168
D:\gtee\C-learning-code-and-project\test_922\Debug\test_922.exe ( process 22660) Exited , The code is 0.
Press any key to close this window . . .
816432_a230_b525_c1015_d30432_d88- The members of a segment can be
int unsigned intsigned intOr is itchar( It belongs to the plastic family ) type
- The space of the bit segment is based on 4 Bytes (
int) perhaps 1 Bytes (char) The way to open up .
- Bit segments involve many uncertainties , Bit segments are not cross platform ,Pay attention to portable program should avoid using bit segment .


intIt's uncertain whether a bit segment is treated as a signed number or an unsigned number .
- The number of the largest bits in the bit segment cannot be determined .(16 The machine is the largest 16,32 The machine is the largest 32, It's written in 27, stay 16 A bit of the machine will go wrong .
- The members in the bit segment are allocated from left to right in memory , Or right to left allocation criteria have not yet been defined .
- When a structure contains two bit segments , The second segment is relatively large , Cannot hold the remaining bits of the first bit segment , Whether to discard the remaining bits or to use , This is uncertain .

2. enumeration
2.1 Enumeration overview
2.1.1 Enumeration concept
2.1.2 Declaration and use of enumeration
enumenum Day// week
{
Mon,
Tues,
Wed,
Thur,
Fri,
Sat,
Sun
};
enum Sex// Gender
{
MALE,
FEMALE,
SECRET
};
enum Color// Color
{
RED,
GREEN,
BLUE
};
Enumeration constants enum Color// Color
{
RED=1,
GREEN=2,
BLUE=4
};
enum Color// Color
{
RED=1,
GREEN=2,
BLUE=4
};
enum Color clr = GREEN;// Only enumeration constants can be assigned to enumeration variables , There will be no type difference .
clr = 5;// error , Enumeration constants cannot be assigned
2.2 Enumeration size calculation
4enum A
{
QSW,
BSW,
CWS
}a;
int main()
{
printf("%d\n", sizeof(a));
return 0;
}
4
D:\gtee\C-learning-code-and-project\test_922\Debug\test_922.exe ( process 21156) Exited , The code is 0.
Press any key to close this window . . .
2.3 The difference between enumeration and macro
#define#define - Increase the readability and maintainability of the code
- and
#defineThe defined identifier comparison enumeration has type checking , More rigorous .
- Prevent named pollution ( encapsulation ).
- Easy to debug .
- Easy to use , You can define more than one constant at a time .
3. Consortium
3.1 Overview of the consortium
3.1.1 Consortium concept
3.1.2 Declaration and use of the consortium
union// Declaration of union type
union Un
{
char c;
int i;
};
// The definition of joint variables
union Un un;
int is_bl()
{
union BL
{
char a;
int b;
}un;
un.b = 1;
// return 1 For the small end , return 0 Big end
if (un.a == 1)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int ret = is_bl();
if (ret == 1)
{
printf(" The small end \n");
}
else
{
printf(" Big end \n");
}
return 0;
}
The small end
D:\gtee\C-learning-code-and-project\test_922\Debug\test_922.exe ( process 23328) Exited , The code is 0.
Press any key to close this window . . .
3.2 Consortium size calculation
- [ ] The size of the union is at least the size of the largest member .
- [ ] When the maximum member size is not an integral multiple of the maximum number of alignments , It's about aligning to an integer multiple of the maximum number of alignments .
union Un1
{
char c[5];
int i;
};
union Un2
{
short c[7];
int i;
};
// What is the output below ?
printf("%d\n", sizeof(union Un1));
printf("%d\n", sizeof(union Un2));
Un15char1int448Un214short2int44168
16
D:\gtee\C-learning-code-and-project\test_922\Debug\test_922.exe ( process 12864) Exited , The code is 0.
Press any key to close this window . . .
边栏推荐
- Flutter series: offstage in flutter
- How can the new generation of HTAP databases be reshaped in the cloud? Tidb V6 online conference will be announced soon!
- Tell you about mvcc
- Weibo International Edition changed its name to Weibo light sharing Edition
- How to gracefully handle and return errors in go (1) -- error handling inside functions
- 外网访问svn服务器(外网访问部署在云上的svn服务器)
- Abnova多肽设计和合成解决方案
- [2021 "shadow seeking" medical artificial intelligence algorithm competition] Ti-One product use tutorial
- C language - number of bytes occupied by structure
- How to monitor the operation of easygbs service in real time?
猜你喜欢

外网访问svn服务器(外网访问部署在云上的svn服务器)

Abnova荧光原位杂交(FISH)探针解决方案

Multi task video recommendation scheme, baidu engineers' actual combat experience sharing

openGauss 3.0版本源码编译安装指南

Openeuler kernel technology sharing issue 20 - execution entity creation and switching

Kubernetes 资源拓扑感知调度优化

Abnova膜蛋白脂蛋白体解决方案

共建欧拉社区 共享欧拉生态|携手麒麟软件 共创数智未来

web技术分享| 【地图】实现自定义的轨迹回放

The official overclocking tool of Intel XTU supports win11 22h2 and 13th generation core Raptor Lake processors
随机推荐
Easyplayer consumes traffic but does not play video and reports an error libdecoder Wasm404 troubleshooting
15+ urban road element segmentation application, this segmentation model is enough
Discussion on the introduction principle and practice of fuzzy testing
一款支持内网脱机分享文档的接口测试软件
2. in depth tidb: entry code analysis and debugging tidb
openEuler社区理事长江大勇:共推欧拉开源新模式 共建开源新体系
华为云GaussDB(for Redis)揭秘第19期:GaussDB(for Redis)全面对比Codis
What is FTP? What is the FTP address of the ECS?
应用实践 | Apache Doris 整合 Iceberg + Flink CDC 构建实时湖仓一体的联邦查询分析架构
Clang代码覆盖率检测(插桩技术)
How to gracefully handle and return errors in go (1) -- error handling inside functions
How much space does structure variable occupy in C language
Abnova膜蛋白脂蛋白体解决方案
How to spell the iframe address of the video channel in easycvr?
How EDI changes supply chain management
How to do the right thing in digital marketing of consumer goods enterprises?
The use of char[0] and char[1] in C language structure
[receive] new benefits of 60 yuan / year? Lowest in history! Double 11 has now begun to seize resources! Get started quickly!!
Multi task video recommendation scheme, baidu engineers' actual combat experience sharing
web渗透测试----5、暴力破解漏洞--(5)SMB密码破解