当前位置:网站首页>015 basics of C language: C structure and common body
015 basics of C language: C structure and common body
2022-06-27 04:24:00 【Prison plan progress 50%】
List of articles
One :C Language structure
1.1: summary
The previous chapter learned about arrays , It is a set of data of the same type . But in the actual programming process , We often need a different set of data , For example, for student information registration form , The name is a string , The student number is an integer , Age is an integer , The study group is character , The score is decimal , Because of different data types , Obviously, you can't use an array to store .
stay C In language , Structures can be used to store a set of different types of data . Structure is defined as :
struct Structure name {
The variable or array contained in a struct
};
A structure is a collection , It contains multiple variables or arrays , They can be of the same type , It can be different , Each such variable or array is called a member of a structure .
struct stu{
char *name; // full name
int num; // Student number
int age; // Age
char group; // Study Group
float score; // achievement
};
Notice the semicolon after the braces ; It can't be less , This is a complete statement .
image int、float、char Wait is by C The data types provided by the language itself , No more spin offs , We call it the basic data type ; The structure can contain multiple basic types of data , It can also contain other structures , We call it complex data type or constructed data type .
1.2: Structural variable
Since the structure is a data type , Then you can use it to define variables . for example ;
struct stu stu1, stu2;
Two variables are defined stu1 and stu2, They are all stu type , All by 5 Members make up . Pay attention to keywords struct It can't be less .
struct stu{
char *name; // full name
int num; // Student number
int age; // Age
char group; // Study Group
float score; // achievement
} stu1, stu2;
1.3: Acquisition and assignment of members
Structs are like arrays , It's also a collection of data , It doesn't make much sense to use it as a whole . Arrays use subscripts [] Get a single element , Structures use point numbers . Get a single member .
The format is : Structure variable name . Member name ;
example :
#include <stdio.h>
int main(){
struct{
char *name;
int num;
int age;
char group;
float score;
}stu1;
// Assign values to structure members
stu1.name = "tom";
stu1.num = 12;
stu1.age = 22;
stu1.group = 'A';
stu1.score = 123.5;
// Read the value of the structure member
printf("%s The student number of is :%d, Age is %d, stay %c Group , This year's achievement is %.1f \n", stu1.name, stu1.num, stu1.age, stu1.group,stu1.score);
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# ./jiegoutichengyuan
tom The student number of is :12, Age is 22, stay A Group , This year's achievement is 123.5
In addition to assigning values to members one by one , You can also assign values as a whole when defining , for example ;
struct{
char *name;
int num;
int age;
char group;
float score;
} stu1, stu2 = {
"tom", 12, 22, 'A', 123.5};
It should be noted that , A struct is a custom data type , Is a template for creating variables , It doesn't take up memory space ; Structural variables contain real data , Memory space is required to store .
Two :C Array of language structs
An array of structs , It means that every element in an array is a structure . in application , Structure arrays are often used to represent a group with the same data structure , For example, a class of students , A workshop worker, etc .
example :
struct stu{
char *name; // full name
int num; // Student number
int age; // Age
char group; // Your group
float score; // achievement
}class[5]; // It means that a class has 5 A student
Structure array can be initialized while being defined , for example ;
#include <stdio.h>
struct stu{
char *name; // full name
int num; // Student number
int age; // Age
char group; // Your group
float score; // achievement
}class[5] = {
{
"Li ping", 5, 18, 'C', 145.0},
{
"Zhang ping", 4, 19, 'A', 130.5},
{
"He fang", 1, 18, 'A', 148.5},
{
"Cheng ling", 2, 17, 'F', 139.0},
{
"Wang ming", 3, 17, 'B', 144.5}
};
obtain Wang ming The achievement of :class[4].score;
modify Li ping Study Group :class[0].group = 'B';
3、 ... and :C Language structures and pointers
3.1: Defining structure
A pointer can also point to a structure , The definition is generally in the form of :struct Structure name * Variable name ;
example :
The following is an example of defining a structure pointer :
struct stu{
char *name; // full name
int num; // Student number
int age; // Age
char group; // Your group
float score; // achievement
} stu1 = {
"Tom", 12, 18, 'A', 136.5 };
// Structure pointer
struct stu *pstu = &stu1;
You can also define the structure pointer while defining the structure :
struct stu{
char *name; // full name
int num; // Student number
int age; // Age
char group; // Your group
float score; // achievement
} stu1 = {
"Tom", 12, 18, 'A', 136.5 }, *pstu = &stu1;
Be careful , Structure variable name is different from array name , The array name is converted into an array pointer in the expression , The structure variable name does not , In any expression, it represents the whole set itself , To get the address of the structure variable , Must be preceded by &, So here it is pstu Assignment can only be written :struct stu *pstu = &stu1; Instead of writing :struct stu *pstu = stu1;
We should also pay attention to , Structure and structure variable are two different concepts : A struct is a data type , It's a template for creating variables , The compiler doesn't allocate memory space for it , It's like int、float、char The keywords themselves don't take up memory ; Structure variables contain real data , Only memory is needed to store .
The following is wrong , It is impossible to get the address of a structure name , You can't assign it to another variable :
struct stu *pstu = &stu;
struct stu *pstu = stu;
3.2: Get structure members
Two forms ( equivalent , The latter is usually used , More intuitive ):
(*pointer).memberName
. Has a higher priority than *, also () You can't omit , If omitted, it is equivalent to :*(pointer.memberName)
pointer->memberName
With ->, You can directly go to the structure member through the structure pointer , This is also -> stay C The only use in language
Look at the example :
example 1:
#include <stdio.h>
int main(){
struct{
char *name;
int num;
int age;
char group;
float score;
}stu1 = {
"tom", 12, 18, 'A', 136.5}, *pstu = &stu1;
// Read the values of structure members
printf("%s The student number of is %d, Age is %d, stay %c Group , This year's achievement is %.1f \n", (*pstu).name, (*pstu).num, (*pstu).age, (*pstu).group, (*pstu).score);
printf("%s The student number of is %d, Age is %d, stay %c Group , This year's achievement is %.1f \n", pstu->name, pstu->num, pstu->age, pstu->group, pstu->score);
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# ./jiegoutizhizhen
tom The student number of is 12, Age is 18, stay A Group , This year's achievement is 136.5
tom The student number of is 12, Age is 18, stay A Group , This year's achievement is 136.5
example 2:
#include <stdio.h>
struct stu{
char *name; // full name
int num; // Student number
int age; // Age
char group; // Your group
float score; // achievement
}stus[] = {
{
"Zhou ping", 5, 18, 'C', 145.0},
{
"Zhang ping", 4, 19, 'A', 130.5},
{
"Liu fang", 1, 18, 'A', 148.5},
{
"Cheng ling", 2, 17, 'F', 139.0},
{
"Wang ming", 3, 17, 'B', 144.5}
},*ps;
int main(){
// Find array length
int len = sizeof(stus) / sizeof(struct stu);
printf("Name\t\tNum\tAge\tGroup\tScore\t\n");
for(ps=stus; ps<stus+len; ps++){
printf("%s\t%d\t%d\t%c\t%.1f \n", ps->name, ps->num, ps->age, ps->group, ps->score);
}
return 0;
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# ./jiegoutishuzuzhizhen
Name Num Age Group Score
Zhou ping 5 18 C 145.0
Zhang ping 4 19 A 130.5
Liu fang 1 18 A 148.5
Cheng ling 2 17 F 139.0
Wang ming 3 17 B 144.5
Four :C Language commonality
Structure (struct) Is a construction type or complex type , Can contain multiple members of different types . stay C There is another syntax in the language that is very similar to the structure , It's called Commons (union).
The definition format is :
union Community name {
Member list
};
difference :
Each member of the structure takes up different memory , There is no influence on each other ; And all members of the Commons occupy the same segment of memory , Modifying one member affects all other members .
The memory occupied by the structure is greater than or equal to the total memory occupied by all members ( There may be gaps between members ), The memory occupied by the Commons is equal to the memory occupied by the longest member .
Commons use memory overlay technology , Only one member's value can be saved at the same time , If you assign a value to a new member , It will override the value of the original member .
Commons are also a custom type , You can use it to create variables , for example :
union data{
int n;
char ch;
double f;
};
union data a, b, c;
The above is to define the common body first , Then create variables , You can also create variables while defining a common body :
union data{
int n;
char ch;
double f;
} a, b, c;
Shared body data in , member f Takes up the most memory , by 8 Bytes , therefore data Variable of type ( That is to say a,b,c) It also takes up 8 Bytes of memory .
example :
#include <stdio.h>
union data{
int n;
char ch;
short m;
};
int main(){
union data a;
printf("%d, %d\n", sizeof(a), sizeof(union data) );
a.n = 0x40;
printf("%X, %c, %hX\n", a.n, a.ch, a.m);
a.ch = '9';
printf("%X, %c, %hX\n", a.n, a.ch, a.m);
a.m = 0x2059;
printf("%X, %c, %hX\n", a.n, a.ch, a.m);
a.n = 0x3E25AD54;
printf("%X, %c, %hX\n", a.n, a.ch, a.m);
return 0;
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# ./gongyongti
4, 4
40, @, 40
39, 9, 39
2059, Y, 2059
3E25AD54, T, AD54
This code not only verifies the length of the common body , It also shows that members of the community will interact with each other , Changing the value of one member will affect other members .
边栏推荐
- 渗透测试-目录遍历漏洞
- MySQL development environment
- There are two problems when Nacos calls microservices: 1 Load balancer does not contain an instance for the service 2. Connection refused
- Système de collecte des journaux
- 低代码开发平台NocoBase的安装
- fplan-电源规划
- 百度飞桨“万有引力”2022首站落地苏州,全面启动中小企业赋能计划
- Cultural tourism light show breaks the time and space constraints and shows the charm of night tour in the scenic spot
- [station B up dr_can learning notes] Kalman filter 3
- Microservice system design -- distributed cache service design
猜你喜欢

如何系统学习LabVIEW?

微服务系统设计——分布式缓存服务设计

Fplan powerplan instance

低代码开发平台NocoBase的安装

Système de collecte des journaux

Building lightweight target detection based on mobilenet-yolov4

nignx配置单ip限流

Mobilenet series (4): mobilenetv3 network details
![Promise source code class version [III. promise source code] [detailed code comments / complete test cases]](/img/51/e1c7d5a7241a6eca6c179ac2cb9088.png)
Promise source code class version [III. promise source code] [detailed code comments / complete test cases]

Microservice system design -- service registration, discovery and configuration design
随机推荐
【Unity】UI交互组件之按钮Button&可选基类总结
022 C语言基础:C内存管理与C命令行参数
Ldr6028 OTG data transmission scheme for mobile devices while charging
办公室VR黄片,骚操作!微软HoloLens之父辞职!
ERP需求和销售管理 金蝶
021 C语言基础:递归,可变参数
golang hello 安装环境异常【已解决】
iOS开发:对于动态库共享缓存(dyld)的了解
[array]bm94 rainwater connection problem - difficult
1.5 conda的使用
Office VR porn, coquettish operation! The father of Microsoft hololens resigns!
Interview-01
Common programming abbreviations for orbit attitude
020 C语言基础:C语言强制类型转换与错误处理
[promise I] introduction of promise and key issues of hand rolling
013 C语言基础:C指针
微服务系统设计——服务熔断和降级设计
差点因为 JSON.stringify 丢了奖金...
Nestjs environment variable configuration to solve the problem of how to inject services into interceptors
日志收集系統