C language structure (struct) and Union (Union)

Source: Internet
Author: User

1. Huge role of struct

In the face of a person's large C/C ++ program, we can evaluate the programming experience of the author simply by looking at the usage of struct. Because a large C/C ++ program is required
It involves some (or even a large number) structures for data combination, which can combine the data originally meaning as a whole. To some extent, how can I use struct?
Struct is a sign of distinguishing whether a developer has rich development experience. In the C/C ++ programming of network protocols, communication control, and embedded systems, what we often want to transmit is not a simple byte stream.
(Char array), but a combination of a variety of data, its form is a struct. Experienced developers often save all the content to be transmitted in the char array in order.
Transmission of network packets and other information through pointer offset. This programming method is complex and error-prone. Once the control mode and communication protocol change, the program must be modified in great detail.

An experienced developer uses struct flexibly. For example, assume that three packets need to be transmitted in the network or control protocol, in the format of packeta, packetb, and packetc:

Struct structa

{

Int;

Char B;

};

Struct structb

{

Char;

Short B;

};

Struct structc

{

Int;

Char B;

Float C;

}

An excellent program designer designed the message to be transmitted in this way:

Struct commupacket

{

Int ipackettype; // Message Type flag

Union // one of the three messages is sent each time.

{

Struct structa packeta;

Struct structb packetb;

Struct structc packetc;

}

};

Send struct directly during message transmission
Commupacket is a whole.

Assume that the original form of the sending function is as follows:

// Psenddata: the first address of the byte stream to be sent. ilen: The length to be sent.

Send (char * psenddata, unsigned int
Ilen );

The sender can directly send struct
Sendcommupacket:

Send (char
*) & Sendcommupacket, sizeof (commupacket ));

Assume that the original form of the receiving function is as follows:

// Precvdata: the first address of the byte stream to be sent. ilen: The length to be received.

// Return value: the actual number of bytes received

Unsigned int Recv (char * precvdata,
Unsigned int ilen );

The receiver can directly make the following calls to save the received data in struct.
An instance of commupacket.

In recvcommupacket:

Recv (char
*) & Recvcommupacket, sizeof (commupacket ));

Then determine the Message Type for corresponding processing:

Switch (recvcommupacket.
Ipackettype)

{

Case
Packet_a:


...
// Class A Message Processing

Break;

Case
Packet_ B:

...
// Class B Message Processing

Break;

Case
Packet_c:


... // Class C Message Processing

Break;

}

The most noteworthy of the above procedures is

Send (char
*) & Sendcommupacket, sizeof (commupacket ));

Recv (char
*) & Recvcommupacket, sizeof (commupacket ));

Forced type conversion in: (char
*) & Sendcommupacket, (char
*) & Recvcommupacket: Get the address first and convert it to a char pointer, so that you can directly use the function for processing byte streams.

Using this forced type conversion, we can also facilitate programming. For example, to initialize the memory of sendcommupacket to 0, we can call the standard library function memset () as follows ():

Memset (char
*) & Sendcommupacket, 0, sizeof (commupacket ));

2. struct member alignment

Companies such as Intel and Microsoft once had a similar interview question:

1. # I nclude
<Iostream. h>

2. # pragma pack (8)

3. struct example1

4 .{

5. Short;

6. Long B;

7 .};

8. struct example2

9 .{

10. Char C;

11. example1 struct1;

12. Short
E;

13 .};

14. # pragma pack ()

15. Int main (INT argc, char *
Argv [])

16 .{

17. example2 struct2;

18. cout
<Sizeof (example1)
<Endl;

19. cout
<Sizeof (example2)
<Endl;

20. cout
<(Unsigned
INT) (& struct2.struct1)-(unsigned
INT) (& struct2)

<
Endl;

21. Return 0;

22 .}

What is the input result of the program?

The answer is:

8

16

4

Do not understand? Still do not understand? Here is one by one:

2.1 Nature

Struct is a composite data type, which can be a variable of the basic data type (such as int, long, float, and so on) or a composite data type (such
Array, struct, Union, etc. For struct, the compiler automatically alignment member variables to improve the computing efficiency. By default, the compiler is
Natural
Alignment) condition to allocate space. Each member is stored in the memory in the declared order. The address of the first member is the same as that of the entire structure.

Natural
Alignment) is the default alignment, which refers to the largest member alignment in the structure.

For example:

Struct naturalalign

{

Char;

Short B;

Char C;

};

In the above struct, short is the largest in size and the length is 2 bytes. Therefore, char members A and C in the struct are aligned in units of 2. sizeof (naturalalign) the result is 6;

If changed:

Struct naturalalign

{

Char;

Int B;

Char C;

};

The result is obviously 12.

2.2 specify the peer

Generally, you can use the following method to change the default peer condition:

· Use pseudoinstructions # pragma pack
(N), the compiler will be aligned according to n Bytes;

· Use the pseudo command # pragma pack () to cancel the custom byte alignment.

NOTE: If # pragma pack
If the value of N specified in (n) is greater than the size of the largest member in the struct, the struct is still bounded by the largest member.

For example:

# Pragma pack (N)

Struct naturalalign

{

Char;

Int B;

Char C;

};

# Pragma pack ()

When N is 4, 8, or 16, the alignment is the same, and the sizeof (naturalign) result is 12. When N is 2, it plays a role, making sizeof (naturalalign) Result 8.

In VC ++
6.0 in the compiler, we can specify its peer mode, and select projetct> setting as its operation method.
> In the C/C ++ menu, specify the peer mode in struct member alignment.



Figure 1: specifying the peer mode in VC ++ 6.0

In addition
(N) can also align the structure members to the n-byte boundary, but it is rarely used, so it is not described in detail.

2.3 answers to interview questions

So far, we can answer intel and Microsoft interview questions comprehensively.

Line 1 in the Program # pragma pack
(8) although the interface is set to 8, the maximum size of the members in struct example1 is 4 (the long variable size is 4 ),
Example1 is still bounded by 4 bytes, and the size of struct example1 is 8, that is, the output result of 18th rows;

Struct example2 contains struct
Example1, the maximum size of the simple data member contained in itself is 2 (short variable E), but because it contains struct
Example1, while the maximum size of struct example1 is 4, struct example2 should also be bounded by 4 pairs, # pragma
The peer field specified in pack (8) does not work for struct example2, so the output result of 19 rows is 16;

Because struct
The members in example2 are bounded in units of 4. Therefore, the char variable C should be followed by three null values, followed by the memory space of the member struct1, and the output result of 20 rows is 4.

 

3. deep differences between struct and C ++

In C ++, struct has the "class" function. The difference between struct and the keyword class is that the default access permission for member variables and functions in struct is public, while the class is private.

For example, define the struct Class and Class class:

Struct structa

{

Char;

...

}

Class classb

{


Char;


...

}

Then:

Struct a;

A. A =
'A ';
// Access the public member, valid

Classb B;

B. A =
'A ';
// Access the private member, illegal

Many documents have written here that all the differences between struct and class in C ++ have been given. In fact, it is not true. Note that:

Struct in C ++ maintains full compatibility with struct in C (which complies with the original intention of C ++-"A Better
C). Therefore, the following operations are legal:

// Define struct

Struct structa

{

Char;

Char B;

Int C;

};

Structa A = {'A', 'A'
, 1 };//
Assign initial values directly when defining

That is, struct can be defined {
} Assign the initial value to its member variables, but the class cannot. In the classic bibliography, thinking C ++ 2nd
The author emphasizes this point in edition.

4. Precautions for struct Programming

Take a look at the following program:

1. # I nclude
<Iostream. h>

2. struct structa

3 .{

4. Int imember;

5. char * cmember;

6 .};

7. Int main (INT argc, char * argv [])

8 .{

9. structa instant1, instant2;

10. Char c = 'a ';

 

11. instant1.imember = 1;

12. instant1.cmember =
& C;

13. instant2 = instant1;

14. cout
<* (Instant1.cmember)
<Endl;

15. * (instant2.cmember) = 'B ';

16. cout
<* (Instant1.cmember)
<Endl;

17. Return 0;

}

The output result of the 14 rows is:

The output result of 16 rows is: B

Why? The modification to instant2 in row 15 changes the value of the Member in instant1!

The reason is that the instant2 of the 13 rows is
The instant1 value assignment statement uses the copy of variables one by one, which enables the cmember in instant1 and instant2 to point to the same piece of memory. Therefore, the modification to instant2 is also a modification to instant1.

In the C language, when the struct contains pointer members, be sure to use the value assignment statement to determine whether to direct the pointer members of the two instances to the same memory.

In C ++, when the struct contains pointer-type members, we need to override the copy constructor of struct and reload the "=" operator.

Else ---------------------------------------------------------------------------------------------------------------------------------

Introduction to the structure (struct) and Union (Union) in C Language

When I saw a friend introduce union, I had never used this thing before, and I didn't understand it. I searched for some information and sent it to everyone. I hope the words in the jar could be corrected or supplemented. Thank you!

Union)

1. Joint description and joint variable definition

Union is also a new data type, which is a special form of variable.

The description of union and the definition and structure of Union variables are very similar. The format is:

Union union Union name {

Data Type member name;

Data Type member name;

...

} Name of the federated variable;

Federated several variables to share a memory location and save different data types at different times
And variables of different lengths.

The following example indicates a combination of a_bc:

Union a_bc {

Int I;

Char mm;

};

You can then define the federated variables with the specified federated variables.

For example, to define a federated variable named lgc using the preceding description, you can write it as follows:

Union a_bc lgc;

In the combined variable lgc, the integer I and the character mm share the same memory location.

When a union is described, the compiler automatically generates a variable,
Its length is the maximum variable length in the Union.

The method and structure for joint access to its members are the same. Likewise, federated variables can be defined as arrays or pointers, but when defined as pointers,
You must also use the "->;" symbol. In this case, the Union access member can be expressed:

Union name->; member name

In addition, a union can appear in a structure, and its members can also be structures.

For example:

Struct {

Int age;

Char * ADDR;

Union {

Int I;

Char * Ch;

} X;

} Y [10];

To access the union member I of X in the structure variable Y [1], you can write it:

Y [1]. X. I;

To access the first character of the string pointer ch that joins X in the structure variable Y [2], you can write it as follows:

* Y [2]. X. ch;

If it is written as "Y [2]. X. * Ch;", it is incorrect.

2. Differences between structure and Union

The structure and combination have the following differences:

1. The structure and union are composed of multiple members of different data types, but at any time,
Only one selected member is stored in the Union conversion, and all Members in the structure exist.

2. assign values to different members of the Union, and rewrite the values of the original members,
The assignment of different members of the structure does not affect each other.

The following is an example of how to understand deep integration.

Example 4:

Main ()

{

Union {

Int I;

Struct {

Char first;

Char second;

} Half;

} Number;

Number. I = 0x4241;

Printf ("% C/N", number. Half. First,
Number. Half. Second );

Number. Half. First = 'a ';

Number. Half. Second = 'B ';

Printf ("% x/N", number. I );

Getch ();

}

Output result:

AB

6261

As shown in the preceding example, after I is assigned a value,
It has eight lower bits, that is, the values of first and second. When the values of first and second are assigned, the ASCII code of these two characters will also be used as the low I

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.