Consortium (community) Union v {...} V;

Source: Internet
Author: User

Http://blog.csdn.net/haiou0/article/details/6903463

Void test ()

{

Union v {

Struct X {

Unsigned char S1: 2 ;//: 2Accounts for twoCharacter? It is two bits.What is int?

Unsigned char S2: 3;

Unsigned char S3: 3;

} X;

Unsigned char C;

} V;

V. C = 100;

Printf ("% d \ n", V. X. S3 );

Printf ("% d \ n", V. X. S2 );

Printf ("% d \ n", V. X. S1 );

}

What is output? How to output? ----> 3 (Press ENTER) 1 (Press ENTER) 0 (Press ENTER)

V is a consortium (shared body) variable. There are two elements X and C, both of which need one byte and they are allocated to the same address. X is a struct variable. There are three elements S1, S2, and S3, which occupy two, three, and three places respectively. The allocated memory low bytes are in the memory low address, and the high bytes are in the high address. When v. C = 100 (its binary value is 01100100), V. the binary value of C is stored in the memory as follows: low bit in the memory and high bit in the memory. The relationships between variables and memory storage are shown in the figure below. In this example, S3, a member of X, is a binary 011, that is, 3 in decimal format. Therefore, the output result is 3.

This is a bit domain problem! X and C in the consortium share one memory space, which is why the Consortium can only save one data type value at a certain time. 100 binary 01100100. (High byte-> low byte) and general machines (general pc cpu) are all small ends, that is, the low byte is in front, so S3 occupies 3 bits 011. The output result is 3

Certificate -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Shared body
Construct a data type, also called a consortium
Purpose: make several different types of variables occupy a portion of memory (overwrite each other)

Struct is a type of constructed data.
Purpose: combine different types of data into a whole ------- Custom Data Type

---------------------------------------------------------------

The Memory Length occupied by struct variables is the total memory length occupied by each member.

The Memory Length occupied by the community variables is the maximum Memory Length occupied by each member (if there is a struct, the total memory of the struct is the same unit.


Which of the following can be stored in a community !!

The members that play a role in the community variables are the last members to be stored,
After new members are saved, the original members become useless!

---------------------------------------------------------------

Structure and Union have the following differences:

1. struct and union are composed of multiple members of different data types, but at any time, union only stores one selected member, and all the members of struct exist. In struct, each member occupies its own memory space and they exist at the same time. The total length of a struct variable is equal to the sum of all member lengths. In union, all Members cannot occupy their memory space at the same time, and they cannot exist at the same time. The length of the Union variable is equal to the length of the longest member.

2. Assignment of different members of the union operation will be rewritten to other members. The original value of the union operation does not exist, but the assignment of different members of struct does not affect each other.

For example:

Example:

# Include <stdio. h>

Void main ()
{
Union {/* define a Union */
Int I;
Struct {/* define a structure in the Union */
Char first;
Char second;
} Half;
} Number;
Number. I = 0x4241;/* Union member assignment */
Printf ("% C \ n", number. Half. First, number. Half. Second );
Number. Half. First = 'a';/* assign values to structure members in the Union */
Number. Half. Second = 'B ';
Printf ("% x \ n", number. I );

System ("pause ");
}

Output result:
AB
6261

Analysis:

Union members share the memory.
Union {
Int I;
Struct {
Char first;
Char second;
} Half;
} Number;
Number. I = 0x4241;

Here, the I and half structures share the memory.

After number. I = 0x00001 assigns a value to I, the memory stores 0100 0010 0100 in binary format.
Correspond to the structure in order
Halt. First = 01000010 is converted to 10, which is 66 (ASC code of the letter)
Halt. Second = 01000001 to 10 in hexadecimal format: 65 (ASC code of letter B)
So the output is AB.

The same is true for the following:

========================================================== ========================================

Question 1:
# Include <stdio. h>
Union
{
Int I;
Char X [2];
};
Void main ()
{
A. X [0] = 10;
A. X [1] = 1;
Printf ("% d", A. I );
}
Answer: 266
Question 2:
Main ()
{
Union {/* define a Union */
Int I;
Struct {/* define a structure in the Union */
Char first;
Char second;
} Half;
} Number;
Number. I = 0x4241;/* Union member assignment */
Printf ("% C \ n", number. Half. First, mumber. Half. Second );
Number. Half. First = 'a';/* assign values to structure members in the Union */
Number. Half. Second = 'B ';
Printf ("% x \ n", number. I );
Getch ();
}
Answer: A 6261

The concept of union in C is that multiple data types in a consortium share the same memory space. For example:
Union
{
Int I;
Char X [2];
};
Consortium A defines two data types, character array X and integer variable I. the integer variable is 16 bits, and the array size is 8x2 = 16 bits. In this way, the compiler will open up a 16-bit space for Consortium A in the memory, which stores the data of the consortium, but this space is only 16 bits, it is both an integer variable data and a character array data. If your program parses the space from the character array perspective, it is two characters. If your program parses the space from the integer perspective, it is an integer.
Taking your program as an example, we have opened up a 16-bit space. Then we assume that the space has not been assigned a value yet, which is:
00000000 00000000
After running the code
A. X [0] = 10;
A. X [1] = 1;
Then, the 16-bit space is changed:
00000110 00000001
Then run the program
Printf ("% d", A. I );
Consortium A is parsed as an integer rather than a string array. In this way, the program converts the 16 bits into a complete INTEGER:
(00000001 00000110) binary = (266) decimal
Note: You can see that when the program converts 16 digits into integers, the last eight digits are placed in front and the first eight digits are placed in the back. This reverse order is caused by the computer storage structure, which has no direct relationship with the consortium. If you are interested, refer to the assembly language.
This is the truth.

In the second example,
Union {/* define a Union */
Int I;
Struct {/* define a structure in the Union */
Char first;
Char second;
} Half;
} Number;

Defines the Union number, which has two data types: integer I (16 bits) and struct (struct half) (2 char, 16 bits ). Therefore, the compiler opens up a 16-bit space for this consortium:
00000000 00000000
Then assign the value:
Number. I = 0x4241;
At this time, the Consortium appears as an integer, and the 16-bit space is regarded as an integer value assignment.
Note (0x4241) (hexadecimal) = (01000010 01000001) binary. Do you still remember what I just said: is the computer stored in reverse mode? First, the low level is saved, and then the high level is saved (refer to the Assembly Language). Therefore, the 16-bit address is assigned a value.
01000001 01000010
Then
Printf ("% C \ n", number. Half. First, mumber. Half. Second );
In fact, the 16-bit space is parsed from the half perspective, that is, two char.
So the first one: Number. Half. First = (01000001) binary = (65) decimal = a (ASCII code)
Similarly, number. Half. Second = B (ASCII code)
Of course, the first and second spaces are assigned to "A" and "B". In this way, the 16-bit space is converted:
01100001 01100010
Then use
Printf ("% x \ n", number. I );
It is to regard 16 bits as integers, and remember that the high position is the opposite.
(01100010 01100001) binary = (0x6261) hexadecimal
So the result is: 0x6261.

Getch ();
Finally, press any key to end the program.

========================================================== ======================================

Question 1: Write a c function. If the processor is big_endian, 0 is returned. If the processor is little_endian, 1 is returned.

Answer:

Int checkcpu ()
{
{
Union W
{
Int;
Char B;
} C;
C. A = 1;
Return (C. B = 1 );
}
}

Analysis:

Embedded system developers should be familiar with the little-Endian and big-Endian modes. In little-Endian mode, the number of CPUs is stored in bytes from low to high, while in big-Endian mode, the number is stored in bytes from high to low. For example, the storage method of 16-bit 0x1234 in little-Endian mode CPU memory (assuming that it starts from address 0x4000) is:

Memory Address Store content
Zero X 4000 0x34
Zero X 4001 0x12

In big-Endian mode, the CPU memory is stored as follows:

Memory Address Store content
Zero X 4000 0x12
Zero X 4001 0x34

32-bit-width 0x12345678 storage method in the little-Endian mode CPU memory (assuming it starts from address 0x4000:

Memory Address Store content
Zero X 4000 0x78
Zero X 4001 0x56
Zero X 4002 0x34
Zero X 4003 0x12

In big-Endian mode, the CPU memory is stored as follows:

Memory Address Store content
Zero X 4000 0x12
Zero X 4001 0x34
Zero X 4002 0x56
Zero X 4003 0x78

The storage order of union Union is that all members are stored from the low address. The interviewer's answer uses this feature to easily obtain the CPU reads and writes to the memory in the little-Endian or big-Endian mode. If anyone could give this answer on the spot, it would be a talented programmer.

Question 2: Write a function and return 1 + 2 + 3 +... + N value (assuming that the result does not exceed the range of long integer variables)

Answer:

Int sum (int n)
{
Return (long) 1 + n) * n/2; // or return (1l + n) * n/2;
}

Analysis:

The simplest answer is the best one. The following answers, or optimization based on the following solutions, cannot be compared with direct return (1 L + n) * n/2 no matter how hard it is!

Int sum (int n)
{
Long sum = 0;
For (INT I = 1; I <= N; I ++)
{
Sum + = I;
}
Return sum;
}

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.