C Language Basics Tutorial (iv) Pointers, structures, unions, and enumerations (15)

Source: Internet
Author: User

Union (Union)

1. Joint notes and joint variable definitions
Union is also a new type of data, which is a special form of variable.
The joint description and the union variable definitions are very similar to the structure. In the form of:
Union Union name {
Data type member name;
Data type member name;
...
Union variable name;
A union represents several variables common to one memory location, which holds different data types and variables of varying lengths at different times.
The following example shows a joint A_BC:
Union a_bc{
int i;
char mm;
};
You can then define union variables with the indicated union.
For example, a union variable named LGC is defined with the union described above, which can be written as:
Union A_BC LGC;
In union variable LGC, integer i and character mm share the same memory location.
When a union is described, the compiler automatically produces a variable of the length of the largest variable in the union.
The method of joint access to its members is the same as the structure. The same union variable can also define an array or pointer, but when defined as a pointer, it also uses the "->" symbol, at which point the federated access member can be represented as:
Union name-> member name
In addition, a union can appear within a structure, and its members can also be structs.
For example:
struct{
int age;
Char *addr;
union{
int i;
Char *ch;
}x;
}Y[10];
To access member I of Union x in struct variable y[1], you can write:
Y[1].X.I;
To access the string pointer to union x in struct variable y[2] The first character of CH characters is written as:
*y[2].x.ch;
If written "Y[2].X.*CH;" Is wrong.

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.