当前位置:网站首页>Part II - C language improvement_ 7. Structure
Part II - C language improvement_ 7. Structure
2022-07-26 23:26:00 【qq_ forty-three million two hundred and five thousand two hundr】
7.1 Basic knowledge of structure
7.1.1 Definition of structure type
struct Person
{
char name[64];
int age;
};
typedef struct _PERSON
{
char name[64];
int age;
}Person;Be careful : When defining a structure type, do not directly assign values to members , Structure is just a type , The compiler hasn't allocated space for it yet , Only when a variable is defined according to its type , To allocate space , You can assign values only when there is space .
7.1.2 The definition of structural variables
struct Person
{
char name[64];
int age;
}p1; // Define types and variables
struct
{
char name[64];
int age;
}p2; // Define types and variables
struct Person p3; // Define directly by type 7.1.3 Initialization of structure variables
struct Person
{
char name[64];
int age;
}p1 = {"john",10}; // Define types and initialize variables
struct
{
char name[64];
int age;
}p2 = {"Obama",30}; // Define types and initialize variables
struct Person p3 = {"Edward",33}; // Define directly by type 7.1.4 Use of structural members
struct Person
{
char name[64];
int age;
};
void test()
{
struct Person p1; // Allocate space on the stack
strcpy(p1.name, "John");
p1.age = 30;
printf("%s %d\n", p1.name, p1.age); // If it's a normal variable , Manipulate structure members through point operators
// Allocate space on the heap
struct Person* p2 = (struct Person*)malloc(sizeof(struct Person));
strcpy(p2->name, "Obama");
p2->age = 33;
printf("%s %d\n", p2->name, p2->age); // If it's a pointer variable , adopt -> Operation structure member
}Output results
John 30
Obama 337.1.5 Structure assignment
7.1.5.1 Basic concept of assignment
The same two structure variables can be assigned to each other , Copy the value of a structure variable to another structure , These two variables are also two independent variables .
struct Person
{
char name[64];
int age;
};
void test()
{
// Allocate space on the stack
struct Person p1 = { "John" , 30};
struct Person p2 = { "Obama", 33 };
printf("%s %d\n", p1.name, p1.age);
printf("%s %d\n", p2.name, p2.age);
// take p2 The value of is assigned to p1
p1 = p2;
printf("%s %d\n", p1.name, p1.age);
}Output results
John 30
Obama 33
Obama 337.1.5.2 Deep copy And light copies
// A teacher has N A student
typedef struct _TEACHER
{
char* name;
}Teacher;
void test()
{
Teacher t1;
t1.name = malloc(64);
strcpy(t1.name , "John");
Teacher t2;
t2 = t1;
// For manually opened memory , You need to manually copy
t2.name = malloc(64);
strcpy(t2.name, t1.name);
if (t1.name != NULL)
{
free(t1.name);
t1.name = NULL;
}
if (t2.name != NULL)
{
free(t2.name);
t1.name = NULL;
}
}7.1.6 Array of structs
struct Person
{
char name[64];
int age;
};
void test()
{
// Allocate space on the stack
struct Person p1[3] =
{
{ "John", 30 },
{ "Obama", 33 },
{ "Edward", 25}
};
struct Person p2[3] = { "John", 30, "Obama", 33, "Edward", 25 };
for (int i = 0; i < 3;i ++)
{
printf("%s %d\n",p1[i].name,p1[i].age);
}
printf("-----------------\n");
for (int i = 0; i < 3; i++)
{
printf("%s %d\n", p2[i].name, p2[i].age);
}
printf("-----------------\n");
// Allocate an array of structures on the heap
struct Person* p3 = (struct Person*)malloc(sizeof(struct Person) * 3);
for (int i = 0; i < 3;i++)
{
sprintf(p3[i].name, "Name_%d", i + 1);
p3[i].age = 20 + i;
}
for (int i = 0; i < 3; i++)
{
printf("%s %d\n", p3[i].name, p3[i].age);
}
}Output results
John 30
Obama 33
Edward 25
-----------------
John 30
Obama 33
Edward 25
-----------------
Name_1 20
Name_2 21
Name_3 227.2 Structure nested pointers
7.2.1 Structure nesting one level pointer
struct Person
{
char* name;
int age;
};
void allocate_memory(struct Person** person)
{
if (person == NULL)
{
return;
}
struct Person* temp = (struct Person*)malloc(sizeof(struct Person));
if (temp == NULL)
{
return;
}
temp->name = (char*)malloc(sizeof(char)* 64);
strcpy(temp->name, "John");
temp->age = 100;
*person = temp;
}
void print_person(struct Person* person)
{
printf("%s %d\n",person->name,person->age);
}
void free_memory(struct Person** person)
{
if (person == NULL)
{
return;
}
if ((*person)->name != NULL)
{
free((*person)->name);
(*person)->name = NULL;
}
free((*person));
}
void test()
{
struct Person* p = NULL;
allocate_memory(&p);
print_person(p);
free_memory(&p);
}Output results
John 1007.2.2 Structure nested secondary pointers
// A teacher has N A student
typedef struct _TEACHER
{
char name[64];
char** students;
}Teacher;
void create_teacher(Teacher** teacher,int n,int m)
{
if (teacher == NULL)
{
return;
}
Teacher* teachers = (Teacher*)malloc(sizeof(Teacher)* n); // Create an array of teachers
if (teachers == NULL)
{
return;
}
int num = 0;
for (int i = 0; i < n; i ++) // Assign students to each teacher
{
sprintf(teachers[i].name, " teacher _%d", i + 1);
teachers[i].students = (char**)malloc(sizeof(char*) * m);
for (int j = 0; j < m;j++)
{
teachers[i].students[j] = malloc(64);
sprintf(teachers[i].students[j], " Student _%d", num + 1);
num++;
}
}
*teacher = teachers;
}
void print_teacher(Teacher* teacher,int n,int m)
{
for (int i = 0; i < n; i ++)
{
printf("%s:\n", teacher[i].name);
for (int j = 0; j < m;j++)
{
printf(" %s ",teacher[i].students[j]);
}
printf("\n");
}
}
void free_memory(Teacher** teacher,int n,int m)
{
if (teacher == NULL)
{
return;
}
Teacher* temp = *teacher;
for (int i = 0; i < n; i ++)
{
for (int j = 0; j < m;j ++)
{
free(temp[i].students[j]);
temp[i].students[j] = NULL;
}
free(temp[i].students);
temp[i].students = NULL;
}
free(temp);
}
void test()
{
Teacher* p = NULL;
create_teacher(&p,2,3);
print_teacher(p, 2, 3);
free_memory(&p,2,3);
}Output results
teacher _1:
Student _1 Student _2 Student _3
teacher _2:
Student _4 Student _5 Student _67.4 Structure byte alignment
In use sizeof Operator to calculate the space occupied by a structure , It's not simply adding up the space occupied by all the elements in the structure , This is about byte alignment in memory .
In theory , Access to any variable can start at any address , But it's not , In fact, accessing a specific type of variable can only be accessed at a specific address , This requires each variable to be arranged in space according to certain rules , Instead of simply sequencing , This is it. Memory alignment .
7.4.1 Memory alignment
7.4.1.1 Memory alignment reason
We know that the smallest unit of memory is a byte , When cpu When reading data from memory , Is a byte by byte read , So the memory for us should be as follows :

But actually cpu Treat memory as multiple blocks , Read one block from memory at a time , The size of this block may be 2、4、8、16 etc. , Then below , Let's analyze the advantages and disadvantages of non memory alignment and memory alignment ?
Memory alignment is the strategy of the operating system to improve the efficiency of accessing memory . When the operating system accesses memory , Read a certain length each time ( This length is the operating system's default alignment number , Or an integer multiple of the default alignment number ). If it's not aligned , In order to access a variable, a second access may occur .
So far, you should be able to simply understand , Why simple memory alignment ?
|
7.4.1.1 How to align memory
- For standard data types , Its address can only be an integral multiple of its length .
- For non-standard data types , For example, structure , Follow the alignment principle :
1. Array member alignment rules . The first array member should be placed in offset by 0 The place of , In the future, each array member should be placed in offset by min Starting at an integer multiple . 2. The total size of the structure , That is to say sizeof Result , Must be min( The largest member inside the structure ) Integer multiple , Make up for deficiencies . 3. Alignment rules of structures as members . If a structure B Nested in another structure A, Or align with the size of the largest member type , But the structure A As the starting point for A An integer multiple of the largest internal member .(struct B There is something inside struct A,A Are there in char,int,double Wait for members , that A It should be from 8 The integer times of start to store .), Structure A The alignment rules of members in still meet the principle 1、 principle 2. |
Manually set the alignment modulus :
1.#pragma pack(show) Show the current packing alignment Bytes of , With warning message Is shown in the form of . 2.#pragma pack(push) Set the currently specified packing alignment Stack the array , The stack here is the internal compiler stack, At the same time, set the current packing alignment by n; If n Is not specified , The current packing alignment Array stack . 3.#pragma pack(pop) from internal compiler stack Delete the top reaord; If not specified n, The top of the current stack record It's the new packing alignement The number ; If you specify n, be n Become the new packing alignment value 4.#pragma pack(n) Appoint packing The numerical , In bytes , The default value is 8, The legal values are 1,2,4,8,16. |
7.4.2 Memory alignment case
#pragma pack(8)
typedef struct _STUDENT
{
int a;
char b;
double c;
float d;
}Student;
typedef struct _STUDENT2
{
char a;
Student b;
double c;
}Student2;
void test01()
{
//Student
//a From the offset 0 Location begins to store
//b from 4 Location begins to store
//c from 8 Location begins to store
//d from 16 Position open storage
// therefore Student The size after internal alignment is 20, The whole must be an integer multiple of the maximum type , That is to say 8 The integral multiple of is 24
printf("sizeof Student:%d\n",sizeof(Student));
//Student2
//a The offset from is 0 Position start
//b The offset from is Student The internal maximum member starts with an integer multiple , That is to say 8 Start
//c from 8 Starting at an integer multiple of , That is to say 32 Start
// Structure Sutdnet2 The size after internal alignment is 40, The whole must be an integer multiple of the maximum type , That is to say 8 Integer multiple 40
printf("sizeof Student2:%d\n", sizeof(Student2));
}Output results
sizeof Student:20
sizeof Student2:32边栏推荐
- 黑马瑞吉外卖之新增员工
- How to recover the original data when the U disk is damaged, and how to recover the damaged data when the U disk is damaged
- 逆袭黑马:数据库全栈工程师(DevDBOps)培训,把最好的课程送给您!
- Database full stack Engineers (devdbops) have low down payment and high return, and pay after employment
- Download win10 system image and create virtual machine on VMware virtual machine
- Regular expressions and bypass case recurrence
- 面试官问:JS的this指向
- 2019 biometric forum successfully ended: these ten highlights should not be missed!
- Restful interface specification
- Typescript notes
猜你喜欢

逆袭黑马:数据库全栈工程师(DevDBOps)培训,把最好的课程送给您!
![[shaders realize distorted outline effect _shader effect Chapter 2]](/img/b3/ab28039cce2521ff1d59f0de6bf852.png)
[shaders realize distorted outline effect _shader effect Chapter 2]

Science | University of Washington uses AI and structural prediction to design new proteins

Programmer growth chapter 29: how to motivate employees?

Ribbon负载均衡

SQL multi table query exercise

Why am I still writing articles on CSDN? A journey of accompanying learning.

SQL Basics

HCIA-R&S自用笔记(18)园区网架构基础、交换机工作原理、VLAN原理

2. Realize the map of navigation bar and battle page
随机推荐
JSON formatting gadget -- pyqt5 instance
Ribbon负载均衡
逆袭黑马:数据库全栈工程师(DevDBOps)培训,把最好的课程送给您!
HCIA-R&S自用笔记(21)STP技术背景、STP基础和数据包结构、STP选举规则及案例
Arduino experiment I: two color lamp experiment
How to use data pipeline to realize test modernization
Ribbon load balancing
华裔科学家Ashe教授对涉嫌造假的Nature论文的正面回应
Restful interface specification
Science | University of Washington uses AI and structural prediction to design new proteins
Differences between PHP round and sprintf functions
Kingbasees SQL language reference manual of Jincang database (3.1.1.3. currency type)
Security team: Recently, there is an rce vulnerability in the COREMAIL email client of windows, which may lead to the disclosure of the private key of the wallet
SQL multi table query exercise
Related functions of strings
30、 Modern storage system (management database and distributed storage system)
Huawei conspires to acquire Brazilian operators?
My SQL is OK. Why is it still so slow? MySQL locking rules
Application of workflow engine in vivo marketing automation | engine 03
Cloud native microservices Chapter 1 server environment description