# Structure, enumeration, union

Posted by Crashthatch on Tue, 21 Sep 2021 12:03:39 +0200

## structural morphology

### 1. Problems of the structure

How are points calculated? First, you must master the alignment rules of the structure:
\1. The first member is at the address offset from the structure variable by 0.
\2. Other member variables shall be aligned to the address of an integer multiple of a number (alignment number).
Alignment number = the compiler default alignment number and the smaller value of the member size.

The default value in VS is 8
The default value in Linux is 4
\3. The total size of the structure is an integer multiple of the maximum alignment number (each member variable has an alignment number).
\4. If a structure is nested, the nested structure is aligned to an integer multiple of its maximum alignment number, and the overall size of the structure is the required size
There is an integer multiple of the maximum number of alignments (including the number of alignments of nested structures).

```struct S4
{
char c1;
struct S3 s3;
double d;
};
printf("%d\n", sizeof(struct S4));

struct S1
{
char c1;
int i;
char c2;
};
printf("%d\n", sizeof(struct S1));

```

Why align

• \1. Platform reason (migration reason): not all hardware platforms can access any data at any address; Some hardware platforms can only work at certain addresses
Get some specific types of data, otherwise throw a hardware exception.
technique
• \2. Performance reason: data structures (especially stacks) should be aligned on natural boundaries as much as possible. The reason is that in order to access misaligned memory, the processor
Two memory accesses are required; Aligned memory access requires only one access.
science and technology

Let the members who occupy less space put together in front.

You can save space and meet alignment requirements

```//For example:
struct S1
{
char c1;
int i;
char c2;
};//12
struct S2
{
char c1;
char c2;
int i;
};//8
```

## Modify alignment number

vs the default alignment is 8;

```#include <stdio.h>
#pragma pack(8) / / set the default alignment number to 8
struct S1
{
char c1;
int i;
char c2;
};
#pragma pack() / / unset the default alignment number and restore it to the default
#pragma pack(1) / / set the default alignment number to 8
struct S2
{
char c1;
int i;
char c2;
};
#pragma pack() / / unset the default alignment number and restore it to the default
int main()
{
//What is the output?
printf("%d\n", sizeof(struct S1));
printf("%d\n", sizeof(struct S2));
return 0;
}

```

## Structural position segment

The declarations of bit segments and structures are similar, with two differences:

1. The member of bit segment must be int, unsigned int, signed int, char family

2. There is a colon and a number after the member of the bit segment. The number represents how many bits are occupied

```Memory allocation for bit segments
1.A member of a bit segment can belong to an integer family (type)
2.The space of bit segment is opened up in the form of 4 bytes or one byte as needed.
3.Bit segment involves many uncertain factors, and bit segment is an uncertain platform
4.stay vs Memory is stored from right to left

```

Function of bit segment: save space and cross platform trouble

Application of bit segment: package the data. This package specifies the size and saves space. The network is like a highway. If everyone saves space, the highway will not be crowded.

Network protocol station, something of the underlying application

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-3cNUAfHO-1632123589736)(C:\Users \ original Yongkang \ Desktop \ screenshot \ CT-20210919061448.png)]

## enumeration

For example, Monday to Sunday

These possible values have values. By default, they start from 0 and increase by 1 at a time. Of course, initial values can also be assigned when defining. For example:

```enum Color//colour
{
RED=1,
GREEN=2,
BLUE=4
};
```

### Why use enumeration

We can use #define to define constants. Why do we have to use enumeration? Advantages of enumeration:
\1. Increase the readability and maintainability of the code
\2. Compared with #define defined identifiers, enumeration has type checking, which is more rigorous.
\3. Prevent naming pollution (packaging)
\4. Convenient for debugging
\5. Easy to use, multiple constants can be defined at a time

### Use of enumerations

```enum Color//colour
{
RED=1,
GREEN=2,
BLUE=4
};
enum Color clr = GREEN;//You can only assign values to enumeration variables with enumeration constants, so that there will be no type difference.
clr = 5; //ok??
```
```void menu()
{
printf("****************************\n");
printf("*********3.mul 4.div********\n");
printf("*********0.exit     ********\n");
printf("****************************\n");
printf("****************************\n");
printf("****************************\n");

}

enum Option
{
exit,
sub,
mul,
div
};
int main()
{

int input = 0;
do
{
scanf("%d", &input);
switch (input)
{
break;
case sub:
break;
case mul:
break;
case div:
break;
case exit:
break;
default:
printf("Input error\n");
break;

}
} while (input);
return 0;

}
```

Enumeration variables can be created with enumeration types. The size is fixed. It is an integer type of 4 bytes, which can be understood as an integer variable

## Union (Consortium type)

### What is a consortium

Consortium type: members in the consortium share the same space, starting from the first address of the space;

### initialization

```union con
{
char a ;
int b=;

};
```

### Determine whether the compiler is large or small

```union con {
int a;
char b;
};
int main()
{
union con u;
u.a = 1;
if (u.b == 1)
{
printf("Small end\n");
}
else
{
printf("Big end\n");
}
return 0;

}
```

### Size of consortium

• The size of the consortium is at least the size of the largest member.

• When the maximum member size is not an integer multiple of the maximum alignment number, it should be aligned to an integer multiple of the maximum alignment number.

For example:

``` union U1
{
char c[5];//5  1
int i ;   //4  4
};  // 8 byte size
```
```union u2
{
short c[7];//14 2
int i ;// 4  4
};// 16 byte size
```

### Comprehensive exercise

mail list
More details here

1. Store information of 1000 people

Information: Name + gender + age + phone + address (complex object creation structure)

3. Delete contact

4. Modification

5. Find

6. Sorting

7. Save to file

## summary

1. The members of a structure can be variables, arrays, pointers, or its own structure (such as a linked list)

2. We can declare multiple variables of the same type with the label of the same structure

3. When members allocate memory, they will be allocated on line according to the alignment rules. In order to save more space, we can arrange members in descending order, which can greatly reduce the storage space.

4. Bit segments cannot be used as platforms because many factors are involved, but bit segments can save a lot of space. (for example, when data is transmitted to the Internet, data packages are allocated through bit segments)

The bit segment stores data from right to left under vs, and one byte or four bytes will be allocated each time,

5. Jointly open up the space for the largest members, and then they share a space

6. What is the difference between members and array elements?

A: structures are collections of different types, and arrays are collections of the same type

Topics: C Linux