Definition and initialization of structure types

The focus of this chapter is: declaration of structure type; self-reference of structure; definition and initialization of structure variables; structure memory alignment; structure parameter passing; structure implementation segment.

Table of contents

Declaration of a structure type:

Self-referencing of struct types

Definition and initialization of structure variables

 Structure memory alignment

Modify the default alignment

Struct parameter passing

struct implementation bit field

bit segment memory allocation

Cross-platform issues with bit segments


Declaration of a structure type:

An array is a collection of elements of the same type; a structure is also a collection of values, and members of a structure can be of different types.

In life: objects are complex, such as a book: title + author + publisher + book number...

struct book                  struct tag
{                            {
    char name[20];               member_list;
    int price; 
    char id[12];
}b4,b5,b6;                   }list;

//b4,b5,b6是全局变量

int main()
{
    struct book b1;
    struct book b2;
    struct book b3;   //b1,b2,b3是局部变量
    return 0;
}

Special structure type; anonymous structure type, can not be fully declared, can only be used once

struct                 //匿名结构体类型
{                      //在声明的时候省略了结构体标签
    char c;
    int i;
}s;
struct 
{
    char c;
    int i;
}* ps;
int main()
{
    ps = &s;            //编译器会将两个声明当成完全不同的类型
    return 0;           //是非法的
}

Self-referencing of struct types

The self-reference of the structure type does not contain variables of the same type but pointers of the same type.

struct N
{
    int d;
    struct N n;
};            //这种写法是错误的,会死循环

Among the data structures (structures in which data is stored in memory) are the following: linear data structures and tree data structures.

Linear data structures are: sequential list and linked list.

Definition and initialization of structure variables

 Structure memory alignment

The default alignment number of vs is 8, and Linux has no concept of default alignment number.

Create a structure, how much space will be allocated to it. The space of the structure should pass the memory alignment principle:

1. The first member is placed at the address of the structure variable offset 0; 2. All members from the second member onwards are placed in an alignment number (the size of the member is smaller than the default alignment number) value) at an address that is an integer multiple of an integer; 3. The total size of the structure is an integer multiple of the largest alignment number among all members of the structure; 4. In the case of nested structures, the nested The structure is aligned to an integer multiple of its maximum alignment number, and the overall size of the structure is an integer multiple of all the maximum alignment numbers (including the alignment number of the structure).

Memory alignment will waste some space, why memory alignment?

1. Platform reasons (transplantation reasons): 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 to access unaligned memory, the processor needs to make two memory accesses; while aligned memory accesses require only one access.

In general, the memory alignment of structures is a practice of exchanging space for time.

When designing the structure, it is necessary to meet the alignment and save space; let the members that occupy a small space be gathered together as much as possible.

Consider the following example:

struct a             struct A
{                    {
    char c1;             char c1;
    int b;               char c2;
    char c2;             int b;
};                   };

The members of the two structures are the same, but the order in which each member is placed is different, resulting in a different size of memory occupied by the two structures. Therefore, the members that occupy small space should be gathered together regardless of the order.

Modify the default alignment

#pragma preprocessing directive

  1. #pragma pack(2)   //修改默认对齐数为2
    struct a
    {
        char c1;
        char c2;
        int b;
    };
    #pragma pack()   //恢复默认对齐数为8
    
    int main()
    {
        return 0;
    }

Conclusion: When the alignment of the structure is inappropriate, we can modify the size of the default alignment number.

Let’s introduce the macro offsetof (refer to the header file <stddef.h>); in cplusplus.com, the definition of the macro offsetof is offsetof(type, member). It is used to calculate the size of the address offset. How is it calculated in the code?

#include <stdio.h>
#incldue <stddef.h>

struct a
{
    char c1;
    int b;
    char c2;
};

int main()
{
    printf("%d\n",offsetof(struct a,c1));       //0
    printf("%d\n",offsetof(struct a,b));        //4
    printf("%d\n",offsetof(struct a,c2));       //8
    return 0;
}

Struct parameter passing

There are two ways to pass structure parameters: passing structure and passing address. Which of these two methods is better?

To transfer a structure, you need to open up another same space to transfer the content of the structure, which is a waste of space and is not efficient; while transferring an address only needs to transfer 4 or 8 bytes, which does not waste too much space and is more efficient. Therefore, it is more efficient to pass parameters and transfer addresses in the structure, and basically any function can be realized without wasting space. Pointer variables can also find the structure itself. When a function passes parameters, the parameters need to be pushed onto the stack, which will cause system overhead in time and space. If a structure object is passed, the structure is too large, and the system overhead of pushing parameters to the stack is relatively large, which will lead to a decrease in performance.

Conclusion: When passing parameters of a structure, the address of the structure must be passed.

struct implementation bit field

Let's first introduce the bit segment, which is attached to the structure. The declaration of bit fields is similar to that of structures, but there are two differences:

1. The members of the bit field must be integer types of int, unsigned int, signed int, and char;

2. There is a colon and a number after the member name of the bit field.

struct A
{
    int _a:2;//成员占2个bite位
    int _b:5;//成员占5个bite位
    int _c:10;//成员占10个bite位
    int _d:30;//成员占30个bite位
};

bit segment memory allocation

1. Members of bit segments can be of integer family types, basically the types of bit segments in a structure are the same;

2. The space of the bit field is allocated in 4 bytes (int) or 1 byte (char) as needed. The size of the bit field cannot exceed the size of the int or char type;

3. The bit segment involves many uncertain factors, the bit segment is not cross-platform, and programs that focus on portability should avoid using the bit segment.

Cross-platform issues with bit segments

1. It is uncertain whether the int bit field is blocked as a signed number or an unsigned number;

2. The maximum number in the bit segment cannot be determined. (16-bit machines have a maximum of 16, 32-bit machines have a maximum of 32, written as 27, there will be problems on 16-bit machines.)

3. Whether the members of the bit segment are allocated from left to right or right to left in memory has not been defined;

4. When a structure contains two bit fields, and the second bit field member is too large to accommodate the remaining bits of the first bit field, it is uncertain whether to discard the remaining bits or use them.

Summarize:

Compared with structures, bit segments can achieve the same effect, but can save space better, but there are cross-platform problems.

The smaller the data packets in the network, the better, which is the application of bit segments.

Guess you like

Origin blog.csdn.net/2301_77868664/article/details/130539253