当前位置:网站首页>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 .
边栏推荐
- Advanced Mathematics (Seventh Edition) Tongji University exercises 1-10 personal solutions
- MATLAB | 三个趣的圆相关的数理性质可视化
- Matlab | drawing of three ordinate diagram based on block diagram layout
- Argo Workflows —— Kubernetes的工作流引擎入门
- [array]bm94 rainwater connection problem - difficult
- There are two problems when Nacos calls microservices: 1 Load balancer does not contain an instance for the service 2. Connection refused
- 为什么 C# 访问 null 字段会抛异常?
- PostgreSQL basic command tutorial: create a new user admin to access PostgreSQL
- 深潜Kotlin协程(十五):测试 Kotlin 协程
- [BJDCTF2020]The mystery of ip
猜你喜欢
![[array]bm94 rainwater connection problem - difficult](/img/2b/1934803060d65ea9139ec489a2c5f5.png)
[array]bm94 rainwater connection problem - difficult

Building lightweight target detection based on mobilenet-yolov4

mysql数据库基础:DQL数据查询语言

Kotlin Compose 隐式传参 CompositionLocalProvider

Microservice system design -- microservice invocation design

Microservice system design -- microservice monitoring and system resource monitoring design

Facing the "industry, University and research" gap in AI talent training, how can shengteng AI enrich the black land of industrial talents?
![[BJDCTF2020]The mystery of ip](/img/f8/c3a7334252724635d42c8db3d1bbb0.png)
[BJDCTF2020]The mystery of ip

Mysql database foundation: DQL data query language
![[station B up dr_can learning notes] Kalman filter 2](/img/52/777f2ad2db786c38fd9cd3fe55142c.gif)
[station B up dr_can learning notes] Kalman filter 2
随机推荐
WPF open source control library extended WPF toolkit Introduction (Classic)
2022-06-26:以下golang代码输出什么?A:true;B:false;C:编译错误。 package main import “fmt“ func main() { type
Kotlin Compose compositionLocalOf 与 staticCompositionLocalOf
How can e-commerce products be promoted and advertised on Zhihu?
022 C语言基础:C内存管理与C命令行参数
011 C语言基础:C作用域规则
1.5 conda的使用
微服务系统设计——分布式事务服务设计
Games101 job 7 improvement - implementation process of micro surface material
Knowledge of iPhone certificate structure
日志收集系统
IOS development: understanding of dynamic library shared cache (dyld)
Almost because of json Stringify lost his bonus
Building lightweight target detection based on mobilenet-yolov4
PostgreSQL basic command tutorial: create a new user admin to access PostgreSQL
Cache comprehensive project - seckill architecture
Nignx configuring single IP current limiting
Golang Hello installation environment exception [resolved]
USB DRIVER
微服务系统设计——服务熔断和降级设计