Difference between Union and struct in C Language

Source: Internet
Author: User

In the C language, struct and union are slightly different, especially when sizeof () is used for large hours. Many friends who have just been familiar with the C language are very confused about this, next I will briefly discuss the differences between Union and struct.

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.


Union
{
Int A [5];
Char B;
Double C;

} Air;

Indicates a Union named A. You can use a variable to define the Union variable.

In the combined variable, integer and double types 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.

Union
{
Int I;
Struct
{
Char first;
Char second;
} Half;
 
} Number;


2. Structure Definition

The general form of defining a structure is:
Struct structure name
{
Member Columns
};
A member table consists of several members, each of which is an integral part of the structure. Each member must also be described as follows:
Type specifier member name;
The name of a member must comply with the writing rules of the identifier. For example:
Struct Stu
{
Int num;
Char name [20];
Char sex;
Float score;
};
In this structure definition, the structure is named Stu, which consists of four members. The first member is num, an integer variable; the second member is name, an array of characters; the third member is sex, a character variable; the fourth member is score and a real variable. Note that semicolons after parentheses are indispensable. After the structure is defined, you can describe the variables. All the variables described as the stu structure are composed of the above four members. It can be seen that the structure is a complex data type, which is a set of several Ordered Variables with fixed numbers and different types.


After introducing the basic knowledge of structure and union, we will talk about the sizeof struct and Union evaluation questions today:

Let's take a look at a Huawei interview question:

For example, the following descriptions and definitions are provided:
Typedef Union {long I; int K [5]; char C;} date;
Struct data {int cat; Date cow; double dog;} too;
Date Max;
The execution result of the statement printf ("% d", sizeof (struct date) + sizeof (max); is :____

It should be noted that typedef is just a simple replacement of names, so that the system can be transplanted on different platforms. Please refer to the following example:

/*
Name: typedef
Copyright: Reserved
Author: persever
Date: 02-08-11
Description:
*/
# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
Typedef int example;
Example A = 10; // equals to int A = 10;

Printf ("% d \ n", );
System ("pause ");
}

Explanation: for 32-bit machines, date is a union and variable public space. the maximum variable type is int [5], which occupies 20 bytes. so its size is 20, and data is a struct. Each variable occupies space separately. int4 + date20 + double8
= 32. Therefore, the result is 20 + 32 = 52.

Let's look at the following example:

The following descriptions and definitions are provided:
Typedef Union {double I; int K [5]; char C;} date;
Struct data {int cat; Date cow; double dog;} too;
Date Max;
The execution result of the statement printf ("% d", sizeof (struct date) + sizeof (max); is :____

Before answering this question rashly, let's take a look at a small example:

# Include <stdio. h>
# Include <stdlib. h>
Union
{

Int A [5];

Char B;

Double C;
};
Int main ()
{
Printf ("% d \ n", sizeof ());
System ("pause ");
}

For a, output by sizeof is 24! In Union, variables share the memory, which should take the longest value as the standard, but the result is not the 20 we expected, because the default memory mode of the variables in the Union is used, it must be aligned with the longest double8 bytes, that is, it should be sizeof (A) = 24; so we will change the int A [5] in the Union to int A [6] and the result will remain unchanged, but if we convert the int
A [5] is changed to int A [7], and the result is changed to 32.


In addition, Let's briefly talk about the differences between struct and class:

In my opinion, the only difference is the access permission. The default access permission of the struct is public, and the default access permission of the class is private.

Thank you for your criticism!

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.