The use of the C Language Consortium (Union) and its essential-union

Source: Internet
Author: User

Reprinted from: 53187106

1. The basic characteristics of a consortium union--the same and different as the struct

Union, the Chinese name "union, common Body", in a way similar to the structure of a struct, a data structure, the common Body (union) and struct (struct) can also contain a lot of data types and variables. But the difference is quite obvious: all the variables in the struct (struct) are "coexisting"--the advantage is that "there is the capacity is big", the disadvantage is that the allocation of the structure memory space is extensive, regardless of use, full allocation. The Union (Union) is that each variable is mutually exclusive-the disadvantage is not enough "containment", but the advantage is that memory usage is more granular and flexible, but also saves memory space.

2. Double-edged sword--Multiple access memory paths coexist

1 //Example2#include <stdio.h>3Unionvar{  4         Long intl; 5         inti; 6 }; 7 Main () {8Unionvarv; 9V.l =5; Tenprintf"V.l is%d\n", V.I);  OneV.I =6;  Aprintf"Now V.l are%ld! the address is%p\n",v.l,&V.l);  -printf"Now V.I are%d! the address is%p\n",v.i,&v.i);  - }   the Results: -V.l is 5   -Now V.l is 6! The address is 0xbfad1e2c   -Now V.I is 6! The address is 0xbfad1e2c 

The Union called the common body is really appropriate-it is completely shared with a memory header address, and a variety of variable names can be used at the same time, the operation is also in force. With so much access memory, it really works, but there's no way to block each other--it's like array + subscript and pointer + offset.

In the example above I changed the value of V.I, the result V.l can also read, then maybe I thought v.l is I want to value, because the above mentioned the first address of the Union of the memory is the same, then there is another situation and the above similar:

An int array variable A, a long int (32-bit machine, a long int is 4 bytes, and the same as int) variable B, I even don't assign a value to int variable B, because the data type is the same, I use int variable B to take out the a[0 in int array a completely. Some of the time accidentally used, but also thought to use is variable B ~

This logical error is hard to find (only a little bit better when the data type is far from the other, and a garbled error is easy to find).

3. Union unions and size ends (Big-endian, Little-endian):

1#include <stdio.h>2Unionvar{  3         Charc[4]; 4         inti; 5 }; 6   7 intMain () {8Unionvardata; 9data.c[0] =0x04;//because it is a char type, the number is not too large to calculate the range of ASCII ~Tendata.c[1] =0x03;//write 16 in order to facilitate direct printing in memory value comparison Onedata.c[2] =0x02;  Adata.c[3] =0x11;  - //The array is lower, the address is low, by the address from low to high, the memory content is: 04,03,02,11.  Total Four bytes!  - //and the four bytes as a whole (regardless of type, directly print hex), should be from the memory high address to the low address, 0x11020304, low 04 placed on the low address.  theprintf"%x\n", DATA.I);  -}

Results:
11020304
Proving that my 32-bit Linux is small (Little-endian)

4. The amount of memory space the Union union occupies:

First, the first address of the Union is fixed, so how big is the union altogether? According to some small common sense, do a non-rigorous basic version of the verification it.

According to: Allocating the stack space when the memory address is basically continuous, at least the same type can be guaranteed together, the continuous description, if I get three structures out, their three addresses should be connected, look at the interval of three addresses to know.

1#include <stdio.h>2 Union sizetest{3         intA; 4         Doubleb; 5 }; 6 Main () {7 Union Sizetest Uniona; 8 Union Sizetest Unionb; 9 Union Sizetest Unionc; Ten    Oneprintf"The initial address of Uniona is%p\n",&Uniona);  Aprintf"The initial address of UNIONB is%p\n",&unionb);  -printf"The initial address of Unionc is%p\n",&unionc);  -}

To print, you can see the results:

The initial address of Uniona is 0XBF9B8DF8
The initial address of UNIONB is 0xbf9b8e00
The initial address of Unionc is 0xbf9b8e08

It is easy to see that 8,0,8, this interval is 8 bytes, press double walk.

Afraid of not insurance, and then change, the int to the group, the other unchanged:

1 Union sizetest{  2         int a[];   3         Double b;   4

Print

The initial address of Uniona is 0xbfbb7738
The initial address of UNIONB is 0xbfbb7760
The initial address of Unionc is 0xbfbb7788

88-60=28
60-38=28
Wrong, huh? I'm talking about 16 binary 0x. Then 0x28 is 40 bytes, which is exactly the size of the array A.

Seems to have forgotten a feature--sizeof ()

If you look directly at sizeof, you know the size of the union.

1printf"The sizeof Uniona is%d\n",sizeof(Uniona)); 2printf"The sizeof unionb is%d\n",sizeof(UNIONB)); 3printf"The sizeof Unionc is%d\n",sizeof(Unionc)); 4printf"The sizeof of union is%d\n",sizeof(Union Sizetest));

5. The Union union applies to the occasion:

With that verification in front, it is essential to confirm that the union's memory is divided by the largest variable in the area.

It is also possible to speculate boldly that the use of this Union is the case of each data type variables occupy the same space and the use of the variables at the same time requirements are not high (single from memory use, I feel right).

Like the second Test on the top, an array (or a larger array of int a[100]), and one or several small variables written in a union, it is not necessary to save space is too limited, but also adds some risk (at least the logical risk mentioned above). So, from the memory footprint analysis, this situation is not as straightforward as the struct.

However, in some cases, although not very memory-saving space, but the union's reusability advantages still exist Ah, such as convenient multi-name, this "ambiguity", from some aspects may also be the advantage. Another benefit of this approach is that certain registers or channels can be transported in multiple cases with limited size.

6. Essence & Advanced:

According to the Union fixed first address and the union according to the maximum demand to open a memory space two features, you can find that all the definition of the surface is virtual, the so-called Union Union, is in memory to you zoned a sufficient space, as to how you play ~ It no matter ~! (more than union and Struct,c is not playing address, so use C flexible, also easy to make mistakes)

Yes, the union member variable is equivalent to opening up several interfaces (that is, the union contains variables)! But, you can't use it without opening it? Of course you can use it!

Write a small test:

1#include <stdio.h>2 Union u{3         inti; 4         DoubleD//This union has a size of 8 bytes5 }; 6 Main () {7 Union u UU; 8UU.I =Ten; 9printf"%d\n", UU.I); Ten    One         Char*C;  Ac = (Char*) &uu;//Assign and strongly convert the first address of Union to Char type -c[0] ='a';  -c[1] ='b';  thec[2] ='C';  -c[3] =' /';  -c[4] ='D';  -c[5] ='e';  + //up to C[7] -printf"%s\n", c);//print string "abc" using terminator ' /' +printf"%c%c %c%c%c%c\n"C:0],c[1],c[2],c[3],c[4],c[5]);  A}

The use of the C Language Consortium (Union) and its essential-union

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.