Union and struct

Source: Internet
Author: User

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;

These variables share the same memory location, saving different data types and variables of different lengths at different times. 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 whose length is the maximum variable length in the Union.

The method and structure for joint access to its members are the same. The federated variables can also be defined as arrays or pointers, but they must also use the "->" symbol when defined as pointers. In this case, the Federated 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, the Union transfer only stores one selected member, and all members of the structure exist.

2. assigning values to different members of the Union will be rewritten to other members. The original value of the members does not exist, but the assignment values to different members of the structure do 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;/* Union member assignment */printf ("% C/N", number. half. first, number. half. second); number. half. first = 'a';/* assign a value to the structure member in the Union */number. half. second = 'B'; printf ("% x/N", number. i); getch ();}

Output result:
AB
6261
From the above example, we can see that after I is assigned a value, the lower eight bits are the values of first and second. After first and second are assigned a character, the ASCII code of these two characters will also be used as the low-eight-bit and high-eight-bit I.

There are many examples of such problems. For example, fill in the following form for teachers and students in the school: the "Occupation" of the first-year-old business unit can be divided into "Teachers" and "Students. For a "unit" student, enter the class number, and the teacher should enter a Teaching and Research Section of a department. The class can be expressed in integer type, and the Teaching and Research Section can only be of character type. To add the two types of data to the "unit" variable, you must define "unit" as the "union" of the two types including integer and struct arrays ".

"Union" has some similarities with "structure. But they are essentially different. Each member has its own memory space in the structure. The total length of a structure variable is the sum of the member lengths. In "Union", each member shares a piece of memory space. The length of a federated variable is equal to the longest length of each member. It should be noted that the so-called sharing here does not mean that multiple members are loaded into a joint variable at the same time, but that the joint variable can be assigned to any member value, however, only one value can be assigned at a time. If a new value is assigned, the old value is washed away. For example, if the "unit" variable described above is defined as a Union that can be attached to a "Class" or "Teaching and Research Section", an integer value (class) or a string (Teaching and Research Section) is allowed ). Either assign an integer value or a string, but not both. The definition of the Union type and the description of the Union variable must be defined,
Variables can be described as the Union type.

1. Definition of union

The general form of defining a union type is:

Union name
{
Member table
};

The member table contains several members. The general form of the members is: the name of the member name of the type specifier should comply with the requirements of the identifier.

For example:

  union perdata  {  int class;  char office[10];  };

Defines a union type named perdata, which contains two members, one is an integer, the member is a class, the other is a character array, and the array is named office. After joint definition, you can describe the joint variables. variables described as perdata types can be used to store integer classes or character arrays.

2. Description of Federated Variables

The description of Federated variables is the same as that of structural variables. That is, definitions are defined first and then explained. definitions are both described and directly described. Taking the perdata type as an example, it is described as follows:

Union perdata {int class; char officae [10] ;}; Union perdata a, B; // description A, B is of the perdata type

Or it can be described as follows:

  union perdata  {  int class;  char office[10];  }a,b;

Or it is directly described:

  union  {  int class;  char office[10];  }a,b;

The variables A and B are of the perdata type. The length of the and B variables should be equal to the longest length of the perdata Member, that is, the length of the office array, a total of 10 bytes. For example, if a and B variables are assigned an integer value, only two bytes are used. If a character array is assigned, 10 bytes can be used.

Assignment and use of joint Variables

Assign values to the federated variables only to the members of the variables. The federated variable member is: Federated variable? ?. For example, if a is a variable of the perdata type, you can use a. class or a. Office. You cannot assign values or perform other operations only with the name of the federated variable. It is not allowed to initialize and assign values to the federated variables. The assignment can only be performed in the program? Why can't I find myself running? Can a federated variable be assigned only one member value at a time? Route 8? The value of a federated variable is a member value of the federated variable.

There is a general form for teachers and students. The instructor data includes four items: name, age, occupation, and teaching and research section. There are four students: name, age, occupation, and class.

Program and input personnel data, and then output in a table.

main(){struct{char name[10];int age;char job;union{int class;char office[10];}depa;}body[2];int n,i;for(i=0;i<2;i++){printf("input name,age,job and department/n");scanf("%s %d %c",body[i].name,&body[i].age,&body[i].job);if(body[i].job=='s')scanf("%d",&body[i].depa.class);elsescanf("%s",body[i].depa.office);}printf("name/tage job class/office/n");for(i=0;i<2;i++){if(body[i].job=='s')printf("%s/t%3d %3c %d/n",body[i].name,body[i].age ,body[i].job,body[i].depa.class);elseprintf("%s/t%3d %3c %s/n",body[i].name,body[i].age, body[i].job,body[i].depa.office);}}

In this example, a structure array body is used to store personnel data. The structure has four members. The member item Depa is a union type, which consists of two members, one being an integer class and the other being an array of characters. In the first for statement of the program, enter the data of the person, first enter the name, age, and job of the first three members of the structure, and then identify the job member items, for example, for "S", Depa is associated. class input (assign the class number to the student) or Depa. enter the Office (assign the teaching and research group name to the instructor ).

When using scanf statements, note that any member of the array type, whether a structure member or a federated Member, cannot add the "&" operator before the entry. For example, in line 2 of the program

Body [I]. Name is an array type, and body [I]. Depa. Office in row 22nd is also an array type. Therefore, the "&" operator cannot be added between the two items. The second for statement in the program is used to output the values of each member item:

Summary of this Chapter

1. Structure and union are two types of data. They are an important means for users to define new data types. There are many similarities between the structure and the Union, which are composed of members. Members can have different data types. The member representation is the same. Three methods are available for variable description.

2. In the structure, each member occupies its own memory space and they exist at the same time. The total length of a structure variable is equal to the sum of all member lengths. In the Union, all Members cannot occupy the memory space at the same time, and they cannot exist at the same time. The length of the federated variable is equal to the length of the longest member.

3. "." is a member operator, which can be used to represent Member items. The member can also be expressed using the "->" operator.

4. The structure variable can be used as a function parameter, and the function can also return a pointer variable pointing to the structure. Union variables cannot be used as function parameters, and functions cannot return pointer variables pointing to union. However, you can use a pointer to a federated variable or a federated array.

5. The structure definition can be nested, and the structure can also be associated as members to form the nesting of the structure and 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.