[C/C ++ language entry]-structure

Source: Internet
Author: User

The first two articles have basically finished introducing pointers. I believe you are not so new to pointers. It will not be confused because of the relationship between the pointer and the array. You may not be eager to learn more about it. Today we will introduce the struct.

 

For struct, since it is called struct, we can understand that it is a collection of data to form a structure. For example, a student's information includes student ID, name, class, age, and so on. The information belongs to this student, so we can bind the information together. Form a student entity. It tastes a bit C ++. It is still necessary for us to think about C in this way. Almost everything around us has its own information or composition. For example, what is the efficacy of a drug, and what components can be bound together to form an entity, so that we can easily access every information or composition of these entities in the program. Therefore, when designing a program, we can combine some common features or component element sets to form a struct. For example, our students can write:

Struct sstudent

{

Char name [13]; // name

Char classname [16]; // Class Name

Char age; // age

....

};

 

In this way, the student's living entity gathers all information about him. In this way, you can centrally manage and access every information in it through struct variables. First, let's see how to access:

C language:

Struct sstudent student;
Student. Age = 22;

C ++:

Sstudent student;
Student. Age = 22;

It can be seen from the above that it is very convenient to access a struct member, but also reflects the concept of entity. The age information of the Student Entity is assigned to 22 years old. It is like using a feature of something. This is also an idea of many object-oriented languages. It is to encapsulate the program data in terms of words and structure. We need to operate on a data just like a function using a tool in real life. We can see that the only difference between the above C and C ++ access is that the C ++ version does not need to add the struct keyword before declaring the struct variable, I personally think that later C ++ thought it was unnecessary to write struct again! It's not better to omit it! The two versions are the same in syntax and sense.

 

Struct does not need a name, for example:

Struct

{

Char age;

Char name [16];

} Student, STU [10];

The struct name is omitted here. student is not the name but the struct variable. This is an anonymous struct. There is no difference with normal. The Stu behind it is a struct array. The definition of a common struct can also be declared immediately when the struct is declared. It's just that it's troublesome to define other variables! This is usually fixed or you can use it once without a name.

 

Let's take a look at the struct alias. An alias can be another name.

Typedef struct sstudent
{
Char age;
Char sex;
Char class;
} Stu, * pstu;
The Stu here is the alias of the sstudent struct, which is equivalent to another name. You do not need to add a hateful struct identifier when using it.

Stu student;

Pstu pstuednt; // alias is pointer type

 

Well, the structure is so simple that some data of different types or the same type is managed together to form an entity. This object can also be understood as a struct. Generally, this design aims at the modular structure of the program, which makes it easier to understand the reality, and the computer is actually serving the reality. For another example, our linked list (connecting a group of data strings into a chain, we can access each node in the chain through a pointer, and the image is called a chain, essentially, a group of data is linked together by pointers, which are usually stored in the memory rather than consecutive). For example:

Struct Node

{

Node * pnext;

Char name [16];

};

It is also a struct that contains a pointer and a name. If our name is the name of a student, we will regard this structure as a node. What is a node? You can imagine that I have a very beautiful pearl necklace with many pearls connected together, so every pearl can be considered as a node. A necklace is formed by concatenating multiple nodes. Some readers may think that this metaphor is easy to understand, but it still feels a little abstract in the program. In fact, it cannot be an abstraction. We just want it to be like this. Just like installing a tool, we noticed two real-life words in this sentence: "Install" and "tool ". The so-called tools we use in computers are actually virtualized. These names are just for the sake of image, and the installation is also true, in real life, we use this word only when assembling or installing a part. It is also used in computers to make it easier for everyone to understand visualization. So we don't have to stick to the naming conventions.

 

Well, we have defined a struct as a node. Our goal is to concatenate the names of all the students in the class. If there are 50 students in the class, there will be 50 nodes. Therefore, we must have 50 struct nodes to store the names of these 50 students, and the names of these 50 students can also be found through loop traversal. We have to do this:

Struct node root; // root node (first student node)

Struct node secst; // 2nd student nodes

We have defined two student nodes above. Now we link these two nodes together.

 

Strcpy (root. Name, "masefee ");

Strcpy (secst. Name, "Tim ");

Root. pnext = & secst;

Secst. pnext = NULL;

We have linked the two nodes above. The next pointer of the root node points to secst, And the next pointer of the secst is assigned null here. If you want to point to the next student node, the same is true. Let's look at the hierarchical relationship:

Root --- | ---- name ("masefee ")

| ---- Pnext --- | ---- name ("Tim ")

| ---- Pnext --- | ---- name ......

| ---- Pnext ......

The above hierarchical relationship clearly describes the relationship between these nodes, so that we can form a chain, and we can find any node through traversal. We also call this kind of storage in memory as chained storage. In essence, data blocks are linked together through pointers. Here I only list two nodes.

Question 1: How can we link 50 nodes together? (Note: each node can use malloc to apply for memory space)

 

Through the above description, we have a preliminary understanding of the usage and concept of struct. Let's take a look at the struct pointer (why is it always impossible to leave the pointer without it? The pointer is always an eternal topic in CC ++ ).

Struct node stunode; // struct Node

Struct node * pnode = & stunode;

Strcpy (pnode-> name, "masefee ");

Above, we define a node struct pointer, which points to stunode. Finally, we copy the name of the stunode struct to "masefee ". Similarly, we can use the library function to apply for space. The size is the size of the node structure:

Struct node * pnode = (struct node *) malloc (sizeof (struct node ));

Here we use the malloc function to apply for a piece of memory of the node structure size, and then let the pnode pointer point to this part of space. Therefore, we can write values to this memory.

Strcpy (pnode-> name, "masefee ");

Pnode-> pnext = NULL;

Here, pnext can also point to the memory space applied for in the next section (which can be used to answer question 1). I will not write it here. You need to explore it yourself.

 

Here, we have to talk about the structure alignment, what is the structure alignment, and why it should be alignment. We all know that the memory unit conversion of a computer is calculated based on the power of 2, which is purposeful. Of course, it is for computer execution efficiency. You can imagine that the type of a variable occupies 3 bytes, 5 bytes, and 1 byte. When addressing, computers can reduce the efficiency of such uneven memory. Therefore, by default, the struct uses 4-byte alignment, which means that some variables with less than 4 bytes may be expanded to 4 bytes or merged into 4 bytes with other struct member variables. This wastes a little bit of memory efficiency, which will increase a lot. When it comes to 4 bytes, of course there are 8 bytes, 16 bytes, 1 byte, and 2 bytes aligned. Here we will talk about 4-byte alignment by default, and the rest are the same. Here is an example:

Struct align

{

Char age;

Int num;

};

Sizeof (struct align) =?

Here we find that the result of sizeof is indeed 8, not 5. The reason is that the default value is 4-byte alignment. Here, char occupies 1 byte and INT occupies 4 bytes, first, when the compiler compiles a char, it will find whether there are more bytes around it that can be merged, merge them into 4 bytes in total, or merge a part and then expand a part to Form 4 bytes, however, it is not found here, So age will be extended to 4 bytes, plus 4 bytes of int, a total of 8 bytes.

 

Struct align;
Align. Age = 0xff;
Align. num = 0 xeeeeeeee;

We assume that the distribution in the memory is:

Age num

FF ee

However:

Age num

Ff cc ee

Age contains three more bytes, which is filled with 0xcc when not initialized. Suppose we define it:

Struct align
{
Char age;
Char age1;
Char age2;
Int num;
};

Then age2 will be expanded to 2 bytes, and age age1 age2 will be merged into 3 bytes and then expanded to 4 bytes. Here, sizeof is 8 bytes. For example:

Struct align
{
Char age;
Int num;
Char age1;
};

In this way, the sizeof result will be 12 bytes, and the reason is also very simple. First, when compiling the age, the search will be extended to 4 bytes if it cannot be merged into 4 bytes, similarly, if the age is 0xff, num is 0 xeeeeeeee, age1 is 0xaa, and the memory distribution is:

Ff cc ee AA CC

 

Question 2: Why don't we expand age and age1 to 2 bytes respectively and then merge them into 4 bytes. The struct is 8 bytes in total?

 

 

 

Here is another example.

Struct align
{
Char age;
Double num;
Char age1;
};

The sizeof here will be 24 bytes, because there is still a standard structure alignment. If it is 4 bytes alignment by default, it is common sense that age and age1 can be expanded to 4 bytes respectively, the entire struct is 16 bytes. But the compiler did not do this, but all of them were extended to 8 bytes, because the struct was dealing with alignment problems, alignment is based on the largest basic data member (note that this is the basic data type ). Suppose:

Struct sstudent
{
Int A [2];

}

Struct align
{
Char age1;
Struct sstudent Stu;
};

The align struct is also 12 bytes, not 16 bytes.

 

For example:

Struct sstudent
{
Char A [13];

};

 

Struct align
{
Char age1;
Struct sstudent Stu;
};

Question 3: What is the size of the align struct in the above program? Why?

 

Let's also look at the forced type conversion between struct pointers and any pointers.

Typedef unsigned char byte;

Struct sstudent
{
Byte age;
Byte sex;
Byte Class;
};

 

Byte array [99];
Struct sstudent * pstu;

Array [0] = 0xaa;
Array [1] = 0xbb;
Array [2] = 0xcc;
Pstu = (struct sstudent *) array;

 

In the above section, we assign the first three elements of array to 0xaa, 0xbb, and 0xcc. The purpose is to see whether the three pstu [0] members of the pstu struct pointer are the first three members of the array after forced type conversion. The answer is yes. You can perform debugging and monitoring on your own. After the forced type conversion of this array, pstu [0], pstu [1],..., pstu [31], pstu [32]. There are 33 structured data blocks in total. Similarly, the addition, subtraction, and accumulation similar to pstu ++ will skip the size of the sstudent struct in bytes. The principle is the same as that mentioned in the previous article.

 

In C ++, the struct structure has undergone earth-shaking changes, which is very different from that in C. It is not mentioned here. When we talk about the function, let's talk about the structure of C ++. However, the struct related mentioned in this article is equally valid in C ++.

 

The in-place domain is often used in the struct. I will leave an idea here for the time being. We will discuss bit operations in detail later.

 

Now, this article introduces some preliminary problems. For better understanding. It can be used with more things. In order to use more flexible methods. Come on!

 

[C/C ++ entry series]

[C/C ++ language entry] -- Preface

[C/C ++ language entry] -- Thinking about helloworld

[C/C ++ language entry] -- Basic Data Type

[C/C ++ language entry]-debugging Basics

[C/C ++ language entry]-deep pointer

[C/C ++ Introduction] -- array and pointer

[C/C ++ Introduction] -- Structure

[C/C ++ language entry] -- go deep into Functions

[C/C ++ language entry]-bit operations

[C/C ++ language entry] -- analyzes floating point numbers

[C/C ++ language entry] -- File Operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.