#How to use pragma pack

Time:2021-5-30

Reference article:https://fanxinglanyu.blog.csdn.net/article/details/106616772

1 cause

When defining communication frame structure variables in communication protocol, the compiler will compile each variable with the corresponding maximum number of bytes by default because the structure contains multiple variables and the number of bytes occupied by each variable is different.

There are two problems

1) The waste of memory resources;

2) In the communication frame parsing function, the sizeof function is used to calculate the number of bytes occupied by the structure, which is not the actual byte length.

 

2 Description

When # pragma pack (n) is used to set variables to be aligned in N bytes, there are two forms:

1) N is greater than the number of bytes occupied by the variable, and the offset uses the default alignment;

2) N is less than the number of bytes occupied by the variable, and the offset is a multiple of n.

3 demo

1 #pragma pack (n)
 2 // is equivalent to the above 
 3 //#pragma pack(push,n)
 4 // function: specify n-byte alignment
 5 struct A{
 6 char b;  //1 byte
 7 int a;   //4 bytes
 8 short c; //2 bytes
 9 };
10 //#pragma pack(pop)
11 // equivalent to the following
12 // function: cancels the specified alignment and restores the default alignment
13 #pragma pack()

If the above is aligned by 1 byte, then the value of sizeof (struct a) is 7;

If it is the compiler’s default mode, the value of sizeof (struct a) is 12.

be careful:

1) The # pragma pack (n) must be used with # pragma pack();

2) In general, let n = 1, that is, # pragma pack (1).

 

Recommended Today

Why is reids fast

1. What is redis? Redis is completely open source and complies with the BSD protocol. It is a high-performance key value database. Redis is also one of the most popular NoSQL databases at present. It contains a variety of data structures, supports network, is memory based, and has an optional key value pair storage database […]