Talking about the self-reference of the structure-memory alignment-bit segment

Structure

Structure self-referencing

  1. First of all, self-reference cannot be made inside the structure.

  2. If necessary, you can define a pointer to a structure that points to yourself.

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

Structure memory alignment

rule

  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 the maximum alignments (including the alignment of nested structures).

Why is there memory alignment?

  1. Platform reason: Not all hardware platforms can access any data at any address.

  2. Performance reasons: aligned access once, unaligned processor requires two memory accesses.
    In general: the memory alignment of the structure is the practice of trading space in exchange for time. Therefore, when designing the structure, we must not only meet the alignment, but also save space. It is best to keep the members with small space together as much as possible. , It is better to arrange from small to large occupying space, in addition to some programs, we can also reduce the waste of space by modifying the default alignment number
    .

     #pragma pack()//取消默认对齐数,还原默认对齐数
     #pragma pack(4)//设置默认对齐数为4
    

Bit segment

The declaration of the bit segment is similar to the declaration of the structure, but there are two differences:

  1. The members of the bit field must be int, unsigned int, or signed int.

  2. There is a colon and a number after the member name of the bit field. The number represents how many bits the member occupies.

    struct A {
    	int _a:2;
    	int _b:5;
    	int _c:10;
    	int _d:30;
    };
    int main()
    {
    	printf("%d\n", sizeof(struct A));//8
    	return 0;
    }
    

Analysis:
  A variable of type int has 4 bytes, 32 bits, 2+5+10<32, so abc is put together, d is put in an int alone, so a total of 2 ints, 8 are used Bytes.

The arrangement method refers to this, this is a little endian
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43580319/article/details/112801360