[C language] In-depth understanding of C language data types: a comprehensive analysis from structures to unions and enumerations

Table of contents

1. Structure overview and definition

1. Concept

2. Definition method

Method 1: Define the structure type first, and then define the structure variable

Method 2: Define the structure variable while defining the structure type

Method 3: Define a one-time structure

2. Initialization of structure variables

1. General initialization

2. Clear the structure variable: use memset

3. Keyboard input assigns values ​​to members in the structure variable

 4. Individually operate the members of the structure

 5. Overall assignment between structure variables of the same type

 Three, structure nested structure

Fourth, the structure array 

1. Initial assignment

2. Keyboard input assigns value to the structure

 Five, the structure pointer variable

1. Structure pointer variable

2. Pointer variables of structure array elements

Six, the pointer member of the structure

        1. Pointer members

        2. The pointer member of the structure points to the heap area 

 3. Shallow copy problem

4. The pointer member of the structure in the heap area points to the heap area. (learn)

5. The structure pointer array is in the heap area, the structure is in the heap area, and the structure pointer members are in the heap area (understand) 

Seven, structure memory allocation alignment rules

1. Automatic alignment rules

2. Automatic alignment rules for nested structures

 3. Forced alignment

Eight, the bit field of the structure

1. The concept of bit field

 2. Prevent bit overflow

3. Create another storage unit

 4. Nonsense bit segments

 Nine, shared body union

 10. Enumeration


1. Structure overview and definition

1. Concept

One or more basic types or structured types (arrays) are called data structures , and
a structure is a collection of data of one or more basic types or structured types (arrays) , that is, a collection of data structures .

2. Definition method

A structure definition consists of the keyword  struct  and the structure name

Method 1: Define the structure type first , and then define the structure variable

struct stu
{
    int num;
    char name[10];
};//定义结构体stu
struct stu lucy;//定义结构体变量lucy

Method 2: Define the structure variable while defining the structure type

struct stu
{
    int num;
    char name[10];
}lucy;//定义结构体stu同时定义结构体变量lucy

Method 3: Define a one-time structure

struct 
{
    int num;
    char name[10];
}lucy;

 Note: A structure variable can have the same name as a member.

Member access method: lucy.num (inherited type, int type) lucy.name (char type, the array name represents the address of the first element)

The system does not allocate space when defining a structure type and its members , and the defined type generally cannot assign values ​​to member variables .

2. Initialization of structure variables

1. General initialization

struct stu
{
    int num;
    char name[10];
};
void test()
{    
    //结构体变量的初始化,必须遵循成员的顺序以及类型
    struct stu lucy={100,"lucy"};
    printf("%d %s",lucy.num,lucy.name);
}

2. Clear the structure variable: use memset

3. Keyboard input assigns values ​​to members in the structure variable

 4. Individually operate the members of the structure

 5. Overall assignment between structure variables of the same type

Three ways:

 Three, structure nested structure

definition:

struct stu
{
	int num;
	char name[10];
	struct data data;//嵌套结构体变量data
};
struct data
{
	int year;
	int month;
	int day;
};

Initialization and output:

	struct stu lucy = { 111,"lucy",{2002,3,7} };
	printf("%d %s\n", lucy.num, lucy.name);
	printf("%d %d %d", lucy.data.year, lucy.data.month, lucy.data.day);

Fourth, the structure array 

        Structure array: the essence is an array, each element is a structure

1. Initial assignment

2. Keyboard input assigns value to the structure

 Five, the structure pointer variable

1. Structure pointer variable

        The essence is that the pointer variable stores the address of the structure variable .

2. Pointer variables of structure array elements

Six, the pointer member of the structure

        1. Pointer members

                Pointer variables as members of structures

        2. The pointer member of the structure points to the heap area 

 3. Shallow copy problem

When the structure variable of the same type is assigned as a whole, if there is no pointer member assignment         in the structure, no shallow copy will occur. If there are pointer members in the structure, assignment is easy to cause shallow copy .

        The problem of shallow copy: the assignment of structure variables of the same type causes the pointer members of each structure variable to point to the same heap space , and when each structure independently releases the space pointed to by the pointer members, the same heap space is released more than once . Second-rate

struct stu bob;
bob = lucy;//浅拷贝

        Solution: If there are pointer members in the structure, try to use deep copy .

struct stu bob;
bob.name = (char *)calloc(1, 128);
bob.num = lucy.num;
strcpy(bob.name, lucy.name);

4. The pointer member of the structure in the heap area points to the heap area. (learn)

5. The structure pointer array is in the heap area, the structure is in the heap area, and the structure pointer members are in the heap area (understand) 

#include <stdio.h>
#include<stdlib.h>
struct stu
{
	int num;
	char *name;//指针成员
};
void test()
{
	struct stu **arr=NULL;
	arr=(struct stu **)calloc(5,sizeof(struct stu *));///给结构体指针数组申请堆区空间
	int i = 0;
	for ( i = 0; i < 5; i++)
	{
		//给指针数组中的每个元素 申请结构体堆区空间
		arr[i] = (struct stu*)calloc(1, sizeof(struct stu));
		//每个结构体中的name成员申请堆区空间
		arr[i]->name = (char*)calloc(1, 100);
		arr[i]->num = 10 + i;
		sprintf(arr[i]->name, "姓名%d", i + 1);
	}
	for ( i = 0; i < 5; i++)
	{
		printf("%d %s\n", arr[i]->num, arr[i]->name);
	}
	//释放
	for ( i = 0; i < 5; i++)
	{
		//先释放结构体中的name的指向
		if (arr[i]->name != NULL)
		{	
			
			free(arr[i]->name);
			arr[i]->name = NULL;
		}
		//释放结构体
		if (arr[i] != NULL)
		{	
			free(arr[i]);
			arr[i] = NULL;	
		}
		//释放整个arr指针数组
		if (arr != NULL)
		{
			free(arr[i]);
			arr= NULL;
		}
	}
}

Seven, structure memory allocation alignment rules

1. Automatic alignment rules

(1) The determination of the allocation unit is determined by the maximum length of the basic type in the structure .

(2) Determine the offset of the member

        Member offset = integer multiple of the length of the member's own type . The multiplier is determined by the unoccupied memory space from front to back.

(3) The total size of the structure = an integer multiple of the allocation unit

 Classic case: draw the alignment of the following structures

struct Data
{
    char a;//成员偏移量 =1B*0
    short b;//成员偏移量 =2B*1
    int c;//成员偏移量 =4B*1
    char d;//成员偏移量 =1B*8
    short e;//成员偏移量 =2B*5
};

The largest basic type is int, the allocation unit is 4B, and the memory allocation is aligned:

a b b
c c c c
d e e

Therefore, a total of 12B

2. Automatic alignment rules for nested structures

(1) It is determined that the allocation unit is determined by the largest basic type length among all structures .

(2) Determine the offset of the member

        Ordinary member offset = an integer multiple of the length of the member's own type . times

The overall offset         of the nested structure = the largest integer multiple of the basic type in the structure

The above multiples are determined by the unoccupied memory space from the beginning to the end.

(3) The total size of the structure = an integer multiple of the allocation unit 

   Nested structure size = integer multiple of the largest basic type in the structure

Memory allocation: a total of 16B

a2
a1
b1 b1 b1 b1
c2 c2

 3. Forced alignment

#pragma pack (value) specified alignment value value (value value 2^{n})

(1) Determine the allocation unit = min ( the largest basic type in the structure , value )

(2) Determine the offset of the member Member offset = integer multiple of the member's own type.

(3) The total size of the finishing work structure = an integer multiple of the allocation unit

Eight, the bit field of the structure

1. The concept of bit field

        In the structure, the members in units of bits are called bit segments (bit fields)

 A total of 32 4B

Bit fields of the same type that are not separated by non-bit fields are called adjacent bit fields.

Adjacent bit fields can be compressed. But the number of compressed bits cannot exceed the size of its own type.

The address of the bit field cannot be taken (because: the system allocates the address in bytes)

 2. Prevent bit overflow

        Assignment to a bit field cannot exceed the bit width of the bit field itself 

 

3. Create another storage unit

 4. Nonsense bit segments

 Nine, shared body union

Structure: all members have independent space

Community: All members share the same space

example: 

union Data
{
    char a;
    short b;
    int c;
};

Members abc share the same space, the space size is determined by the largest member space, data is 4B.

Reflect sharing:

 Members abc share the same space, but the range of space that each member can operate is determined by the length of the member's own type

 10. Enumeration

        Enumeration: List the values ​​​​to be assigned to the enumeration variables one by one

Take poker suits as an example to enumerate four suits:

enum POKER_COLOR{ HONGTAO , MEIHUA , FANGKUAI , HEITAO };

If the value of an enumeration list is modified, it will be incremented sequentially from the point of modification.

Guess you like

Origin blog.csdn.net/m0_75045191/article/details/131668172