C language union (of Union)

Structures and unions difference is that: the structure of each member will occupy different memory, does not affect each other; and all members of a union occupy the same memory section, a modification affects all members of the other members.

Structure of the memory occupied by all the members of not less than the sum of the memory consumed (there may be a gap between the members), the common memory occupied by the body member is equal to the longest amount of memory. The union used the memory cover technology, the same time a member can only hold values, if the assignment of the new members will put the value of the original members overwritten.

Union is a self-defined types, which can be created by a variable, for example:

  1. union data{
  2. int n;
  3. char ch;
  4. double f;
  5. };
  6. union data a, b, c;

The above is to define a common body, and then create a variable, the variable can be defined to create the common body at the same time:

  1. union data{
  2. int n;
  3. char ch;
  4. double f;
  5. } a, b, c;

If no new variable is defined, a union may be omitted name:

  1. union{
  2. int n;
  3. char ch;
  4. double f;
  5. } a, b, c;

Union data, the memory occupied by the maximum of f members, is 8 bytes, the data type of the variable (i.e. a, b, c) also occupies 8 bytes of memory, see the following presentation:

  1. #include <stdio.h>
  2. union data{
  3. int n;
  4. char ch;
  5. short m;
  6. };
  7. int main () {
  8. union data a;
  9. printf("%d, %d\n", sizeof(a), sizeof(union data) );
  10. a.n = 0x40;
  11. printf("%X, %c, %hX\n", a.n, a.ch, a.m);
  12. a.ch = '9';
  13. printf("%X, %c, %hX\n", a.n, a.ch, a.m);
  14. a.m = 0x2059;
  15. printf("%X, %c, %hX\n", a.n, a.ch, a.m);
  16. a.n = 0x3E25AD54;
  17. printf("%X, %c, %hX\n", a.n, a.ch, a.m);
  18. return 0;
  19. }

operation result:

4, 4
40, @, 40
39, 9, 39
2059, Y, 2059
3E25AD54, T, AD54

This code is not only verified the size of the union, also described are interactions between the union member, a modification value of the member affects other members.

To understand the above output, figure out exactly how the mutual influence between the members, you have to understand the distribution of individual members in memory. In the above data, for example, distribution of the individual members in memory following:

members n-, ch, m "align" into a memory, to modify the assignment ch is the previous byte, the assignment of the m first two modifications is bytes, to modify the assignment of n is whole bytes. That is, ch, m will affect the part of the data of n, and n will affect all the data ch, m's.

The figure is the distribution of memory on most PC's, if it is 51 single-chip, the situation will be different:

Why different machines have different distributions of it? This machine related with storage mode, we will be in the VIP tutorial " big-endian and little-endian mode discrimination started to explore" section.

Application of a union

Union seldom used in a general programming, in many microcontroller applications. For the PC, to a frequently used example is: a form of existing student information and information about the teacher. Student information including name, message number, sex, occupation, scores of teachers including name, number, gender, occupation, teaching subjects. Consider the following table:

Name on one Sex Profession Score / Course
HanXiaoXiao 501 f s 89.5
YanWeiMin 1011 m t math
LiuZhenTao 109 f t English
ZhaoFeiYan 982 m s 95.0


f and m are women and men, s indicates the student, t represents teachers. As can be seen, the data included students and teachers are different. Now requires this information in the same table, and personnel information and design program input output.

If each person's information as a structure variable, then the teachers and students of the first four members of the variables is the same, the fifth member variables may be score or course. When the value of the fourth member when the variable is s, the fifth member is variable Score; when the value of the fourth member variable t is time, the fifth member is variable course.

After the above analysis, we can design a structure comprising a common member, see the following code:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. TOTAL #define 4 Total number of persons //
  4. struct{
  5. char name[20];
  6. the num an int ;
  7. char sex;
  8. char profession;
  9. union{
  10. float score;
  11. char course[20];
  12. } sc;
  13. } bodys[TOTAL];
  14. int main () {
  15. int i;
  16. // input personnel information
  17. for(i=0; i<TOTAL; i++){
  18. printf("Input info: ");
  19. scanf("%s %d %c %c", bodys[i].name, &(bodys[i].num), &(bodys[i].sex), &(bodys[i].profession));
  20. IF (the bodys [I ] .profession == 'S' ) { // If the student
  21. scanf("%f", &bodys[i].sc.score);
  22. } The else { // If the teacher
  23. scanf("%s", bodys[i].sc.course);
  24. }
  25. fflush(stdin);
  26. }
  27. // output personnel information
  28. printf("\nName\t\tNum\tSex\tProfession\tScore / Course\n");
  29. for(i=0; i<TOTAL; i++){
  30. IF (the bodys [I ] .profession == 'S' ) { // If the student
  31. printf("%s\t%d\t%c\t%c\t\t%f\n", bodys[i].name, bodys[i].num, bodys[i].sex, bodys[i].profession, bodys[i].sc.score);
  32. } The else { // If the teacher
  33. printf("%s\t%d\t%c\t%c\t\t%s\n", bodys[i].name, bodys[i].num, bodys[i].sex, bodys[i].profession, bodys[i].sc.course);
  34. }
  35. }
  36. return 0;
  37. }

operation result:

Input info: HanXiaoXiao 501 f s 89.5↙
Input info: YanWeiMin 1011 m t math↙
Input info: LiuZhenTao 109 f t English↙
Input info: ZhaoFeiYan 982 m s 95.0↙

Name            Num     Sex     Profession      Score / Course
HanXiaoXiao     501     f       s               89.500000
YanWeiMin       1011    m       t               math
LiuZhenTao      109     f       t               English
ZhaoFeiYan      982     m       s               95.000000

Guess you like

Origin www.cnblogs.com/linwenbin/p/10958773.html