(C language) Detailed explanation of custom types-structure

Detailed custom type-structure

(A structure is a collection of values, these values ​​are called member variables. Each member of the structure can be a variable of different types.)

Structure type declaration

For example, describe a student:

struct Stu 
{
    
     
char name[20];//名字 
int age;//年龄 
char sex[5];//性别 
char id[20];//学号 
}//分号不能丢

Special declaration: when declaring the structure, you can not fully declare (omit the structure tag)

//匿名结构体类型
struct
{
    
    
 int a;
 char b;
 float c; }x;
struct
{
    
    
 int a;
 char b;
 float c; }a[20], *p;

Structure self-reference (correct self-reference is best to add a pointer)

struct Node 
{
    
     
int data; 
struct Node* next; 
}; 

Definition and initialization of structure variables

struct Point
{
    
    
 int x;
 int y; }p1; //声明类型的同时定义变量p1
struct Point p2; //定义结构体变量p2
//初始化:定义变量的同时赋初值。
struct Point p3 = {
    
    x, y};
struct Stu        //类型声明
{
    
    
 char name[15];//名字
 int age;      //年龄
};
struct Stu s = {
    
    "zhangsan", 20};//初始化
struct Node
{
    
    
 int data;
 struct Point p;
 struct Node* next; 
}n1 = {
    
    10, {
    
    4,5}, NULL}; //结构体嵌套初始化
struct Node n2 = {
    
    20, {
    
    5, 6}, NULL};//结构体嵌套初始化

Structure memory alignment

Mainly calculate the size of the structure ( popular test site ):
First, you must master the alignment rules of the structure:

  1. The first member is at an address with an offset of 0 from the structure variable.
  2. Other member variables should be aligned to an address that is an integer multiple of a certain number (alignment number).
    Alignment number = the smaller value of the compiler default alignment number and the member size.
    The default value in VS is 8
  3. The total size of the structure is an integer multiple of the maximum alignment (each member variable has an alignment).
  4. If the structure is nested, the nested structure is aligned to an integer multiple of its maximum alignment, and the overall size of the structure is an integer multiple of all maximum alignments (including the alignment of nested structures).
//练习1
struct S1
{
    
               字节   默认值    较小值
	char c1; 1      8        1
	int i;   4      8        4
	char c2; 1      8        1
};
int main()
{
    
    
	printf("%d\n", sizeof(struct S1));
}

Running results
Insert picture description here
Note:
Insert picture description here
Why is there memory alignment?
Most of the reference materials say this:

  1. Platform reason (transplant reason): Not all hardware platforms can access any data at any address; some hardware platforms can only
    fetch certain types of data at certain addresses, otherwise a hardware exception will be thrown.
  2. Performance reasons: Data structures (especially stacks) should be aligned on natural boundaries as much as possible. The reason is that in order to access unaligned
    memory, the processor needs to make two memory accesses; while aligned memory access only requires one access.
    In general:
    the memory alignment of the structure is a practice of trading space for time. Bit Technology
    . When designing the structure, we must not only satisfy the alignment, but also save space. How to do it:
    Let the members with small space be gathered together as much as possible.
    The members of type S1 and S2 are exactly the same, but the size of the space occupied by S1 and S2 is somewhat different.

Structure parameter transfer

for example:

struct S 
{
    
     
int data[1000]; 
int num; 
}; 
struct S s = {
    
    {
    
    1,2,3,4}, 1000}; 
//结构体传参 
void print1(struct S s) 
{
    
     
printf("%d\n", s.num); 
} 
//结构体地址传参 
void print2(struct S* ps) 
{
    
     
printf("%d\n", ps->num); 
} 
int main() 
{
    
     
print1(s);  //传结构体 
print2(&s); //传地址 
return 0; 
}

The print2 function in the print1 and print2 functions is good: when the
function passes parameters, the parameters need to be pushed on the stack, which will cause time and space system overhead.
If the structure is too large when passing a structure object, the system overhead of parameter stacking is relatively large, so it will cause performance degradation.
Conclusion: When passing the structure parameter, the address of the structure must be passed.

Structure to realize bit segment (filling of bit segment & portability)

What is a
bit segment The declaration and structure of a bit segment are similar, with two differences:
1. The members of a bit segment must be int, unsigned int or signed int.
2. There is a colon and a number after the member name of the bit segment.
The ability of the structure to implement bit segments is as follows:
Example:

#include<stdio.h>
#include<string.h>
struct A
{
    
    
	int _a : 2;
	int _b : 5;
	int _c : 10;
	int _d : 30;
};
int main()
{
    
    
	printf("%d\n", sizeof(struct A));
}

A is a bit segment type. (1 byte = 8bit)
What is the size of that segment A? 8 Memory allocation of
running result
Insert picture description here
bit segment

  1. The members of the bit segment can be int unsigned int signed int or char (belonging to the integer family) type
  2. The space of the bit segment is opened up in 4 bytes (int) or 1 byte (char) as needed.
  3. Bit segments involve many uncertain factors. Bit segments are not cross-platform. Programs that focus on portability should avoid using bit segments.
    Cross-platform issues
  4. It is uncertain whether the int bit field is treated as a signed number or an unsigned number.
  5. The number of largest bits in the bit segment cannot be determined. (The 16-bit machine has a maximum of 16, and the 32-bit machine has a maximum of 32. Write it as 27,
    which may cause problems on a 16-bit machine .
  6. The members in the bit segment are allocated from left to right in memory, or the criteria for allocation from right to left have not been defined.
  7. When a structure contains two bit segments, and the second bit segment has a relatively large member and cannot fit in the remaining bits of the first bit segment
    , it is uncertain whether to discard the remaining bits or use them.
    Compared with the structure, the bit segment can achieve the same effect, but it can save space very well, but there is a cross-platform problem .

Guess you like

Origin blog.csdn.net/weixin_44436675/article/details/110298394