Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize types in C language

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to customize the type in C language, which has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let Xiaobian take you to understand it together.

1. Structure 1. Definition and initialization of structure variables

Code directly:

struct Point { int x; int y;}p1; //Create a variable when creating a structure. Semicolon must not drop struct Point p2; //Create variable struct Point p3 = { 1,2 } separately; //When creating a variable, assign struct Node { char str[20]; struct Point p; //struct nesting}n1 = { "abcd",{3,4} };int main() { printf("%s\n", n1.str); //structure access, use. Or->, variable access with., Pointer Access-> printf("%d\n", n1.p.x); printf("%d\n", n1.p.y); return 0;}

struct is the keyword to create a structure, Point is the name of the structure, p1 is a variable of the structure Point, x, y are called the member variables in the structure Point, there are two forms of variable creation, the first, you can create the structure together, the second, create separately, the creation rule is type + name, for the assignment of the structure, you can assign values when creating variables, you can create variables first and then assign values separately. There are two ways to access a struct. When using variables, use. (dot), and then select the corresponding attribute of the variable; when using the pointer to access, use->, and then select the corresponding attribute.

2. Structure memory alignment

When we want to calculate the memory size of the structure, we need to know the concept of structure diagram memory alignment. Let's first look at two examples:

struct A { char a; char b; int c;};struct B { char a; int c; char b;};int main(){ printf("%d\n", sizeof(struct A)); printf("%d\n", sizeof(struct B)); return 0;}

The results show that the memory occupied by A and B structures is not equal, but their internal member variables are the same, but in different order. The reason why the results are different is because of memory alignment. Let's introduce the rules for memory alignment of structures:

1. The first member is at an address offset 0 from the struct variable.

Other member variables are aligned to addresses that are integer multiples of a number (alignment number). Alignment = the smaller of the compiler default alignment and the member size. In the VS compiler, the default alignment number is 8.

The total size of the struct is an integer multiple of the maximum number of alignments (one for each member variable).

If nested structs are aligned to an integer multiple of their maximum alignment, the entire struct size is an integer multiple of all maximum alignments including nested structs.

3. Why memory alignment?

As we can probably guess from the results above, in order to save space. Overall, there are two main reasons:

1. Platform reasons:

Some hardware platforms can only fetch addresses at specific addresses, there is no memory alignment, and errors may occur when fetching values.

2. Performance reasons:

For misaligned cases, it may be necessary to read the data twice when reading, as shown in the following figure:

On a 32-bit platform, if you want to read 4 bytes of int in the case of misalignment, you will read one byte of char and the last 3 bytes of int (small end) for the first time, and you need to read it again to read the 4 bytes of int completely; in contrast, if you are in the case of memory alignment, you can read the 4 bytes of int directly.

II. Segment

The struct also has the ability to implement a bit segment, so the question is, what is a bit segment?

1. What is a segment?

The declarations and structs of bit segments are similar, but differ in two ways:

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

The member name of a field is followed by a colon and a number.

For example:

struct A{ int _a:2; int _b:5; int _c:3; int _d:4;};

A is a bit field type. If you want to know the size of A, you can also use sizeof to find it.

2. memory allocation for bit segments

Take the bit segment A above, for example, it will first open up a 4-byte space in memory. The number after the colon indicates the size of the memory occupied by the member variable. The unit is bit. The members in the bit segment are allocated from left to right in memory. When a structure contains two bit segments, the second bit segment member is relatively large and cannot accommodate the remaining bits in the first bit segment. It is uncertain whether to discard the remaining bits or use them. In general, segments achieve the same effect as structures, but save space well, but there are cross-platform problems. It's not easy to understand. Let's look at the following picture:

Of course, although bit segments save more memory than structs, they have cross-platform problems and need to be used with caution.

Enumeration 1. Definition of enumeration enum Day//Week { Mon, //By default, Mon value is 0, and the values of the following member variables are incremented in turn Tues, Wed, Thur, Fri, Sat, Sun};

Of course, you can also assign values at the time of definition, for example:

enum Color//Color { RED=1, GREEN=2, BLUE=4};2. Advantages of enumeration

We know that #define can define constants, so why use enumerations?

Advantages of enumeration:

1. Increase code readability and maintainability

2. The identifiers defined with #define are more rigorous than enumerations with type checking.

3. Easy to use, multiple constants can be defined at once

Since it exists, there is a reason for its existence. Sometimes #define is more convenient. Sometimes enumeration is more convenient. We must learn to use it reasonably.

4. Union (community) 1. Definition of union type union Un //Declare { char c; int i;};union Un un; //Define variable printf("%d\n", sizeof(un)); //Calculate the size of the community 2. Characteristics of union

The members of a union share the same block of memory space, so that the size of a union variable is at least the size of the largest member (because the union must at least be able to hold the largest member).

union Un{ int i; char c;};union Un un;//Is the output the same? printf("%d\n", &(un.i));printf("%d\n", &(un.c));//What is the output below? un.i = 0x11223344;un.c = 0x55;printf("%x\n", un.i);

It turns out that the addresses of i and c are the same, because they share a space, and when i and c are assigned separately, the later c overrides some of the values of the previous i.

3. Calculation of joint size

The size of the union is at least the size of the largest member.

When the maximum member size is not an integer multiple of the maximum alignment, align to an integer multiple of the maximum alignment.

For example:

union Un1{ char c[5]; int i;};union Un2{ short c[7]; int i;};//What is the output below? printf ("%d\n", sizeof(union Un1)); //8, c is 5 bytes, larger than i, the maximum alignment digit is 4, it needs to be a multiple of 4, so it is 8printf ("%d\n", sizeof(union Un2)); //16, c accounts for 14 bytes, the maximum alignment number is 4, so thank you for reading this article carefully, I hope Xiaobian share "How to customize the type in C language" This article is helpful to everyone, but also hope that everyone will support, pay attention to the industry information channel, more relevant knowledge waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report