Structure Struct and Union union

Source: Internet
Author: User

Structure in the 1.C language

1.1 Definitions

A struct is a collection of variables of the same or different types.

struct struct Name {//struct is the keyword, struct name is a user-defined type identifier .

Data type 1 member name 1; {} is a member that makes up the struct, where the data type can be any data type allowed by the C language.

Data type 2 member name 2;

...

Data type N member name N;

};

1.2 Memory allocations for structs (method i)

Structs allocate a contiguous amount of memory in memory, but the variables within the structure are not necessarily contiguous, which involves memory alignment.

principle 1 data member Alignment rules: A data member of a struct (struct or union Union), where the first data member is placed at offset 0, where the starting position of each data member store is to begin with an integer multiple of that member size (for example, int is 4 bytes in a 32-bit machine, To start storage from an integer multiple address of 4).

principle 2 struct as a member: if there is some struct member in a struct, the struct member is to be stored from the integer multiple address of its internal maximum element size. (struct A contains elements such as char,int,double in a struct b,b, and that B should be stored in multiples of 8.) )

principle 3 Closing work: The total size of the structure, which is the result of sizeof, must be an integral multiple of the largest member of its interior, not enough to be filled.

Example 1.

structa{structb{intACharb; CharbintA;  ShortC ShortC;                                   }; };sizeof(A) =8int is 4,char for 1,short and 2, principle 1 and Principle 3 are used here. sizeof(B) = A; char is 1,int to 4,short for 2, how can it be 12?           It is also principle 1 and principle 3. Memory layout of a B CA:1111,1*, OneB-A CB memory layout:1***,1111, One**

Where the asterisk * represents the populated bytes.

A, why do you want to add a byte after B? Because C is short, its starting position is a multiple of 2, which is principle 1. There is no supplement to C, since B and C occupy 4 bytes, and the entire a occupies a multiple of 4, that is, a multiple of the maximum member int type, so there is no need to add it.

B, B is a char that adds 3 bytes to the 1,b, since a is an int of 4, and according to Principle 1, the starting position is a multiple of 4, so B is followed by a 3-byte supplement. C is supplemented by two bytes, according to principle 3, the entire B takes up space to be a multiple of 4, after C does not add, the entire B space is 10, does not match, so to add 2 bytes.

Example 2.

structa{structb{intAChare[2]; DoublebintF; floatCDoubleG;                                  };  Shorth; structA i; };sizeof(A) = -int is 4,double to 8,float is 4, the total length is a multiple of 8, and is padded, so the whole A is 24. sizeof(B) = -look at the memory layout of B. The memory layout of E F g H B: One* *,1111,11111111, One* * * * * *, I1111* * * *,11111111,1111* * * *

I'm actually the memory layout of a. The starting position of the 2,i according to the principle should be a multiple of 8, so the h should be followed.

memory allocation of 1.3 structure (method two)

The memory size of a struct is the sums of each data memory, which is first allocated according to the largest data type , and if the previous data does not occupy all of the memory, and the remaining memory can drop the next data , the second data does not allocate additional memory ( But the address must start with an integer multiple of the size of the data type, see struct C below, or reassign a maximum type of memory . (personally think this method is better understanding!) )

Example 3.

structa{structb{structc{intAintAintA; CharbDoublebCharb; DoubleCCharC ShortC;                                   }; };CharD; }

For struct A:
Because the largest data type in a is double, accounting for 8 bytes. So the system first allocates 8 bytes to put int, the result int only need 4 is enough, then the remaining 4 bytes of 1 can be used to put the subsequent char, when the double C, because at this time the 3 bytes can not be saved, so the allocation of a 8 bytes to hold double C. So a takes up 16 bytes.

for struct B:

The system encounters an int to give him 8 bytes to hold, when it touches a double, the remaining 4 bytes are not enough to hold, so 8 bytes are allocated, and then 8 bytes are allocated when the char is encountered, so B is allocated 24 bytes. (The system is actually a waste of 5 bytes of space)

Comparing A and B, the variables are defined in different order, and the result takes up a different memory space. Therefore, the structure of the best in the type from small to large order to avoid wasting space.

for struct C:

According to the above method, the largest data type is int, which is 4 bytes, the system allocates 4 bytes (0~3), allocates 4 bytes (4~7), holds char B, and shortC accounts for 2 bytes, but must start from the integer multiples of 2, so it should be allocated (6~7) . The middle spare 1 bytes, char d is 1 bytes, but the last allocated 4 bytes ran out, so we need to allocate 4 bytes to hold char d,d only 1 bytes, so the remaining 3 bytes are idle. sizeof (struct C) = 12.

2. The difference between a struct and a class in C + +

Structs in C do not allow functions, whereas structs in C + + are allowed.

There is no difference between a class and a struct in C + + only two points apart.

1) The default member access rights in class are private, while structs are public.

2) Inheriting from class is a private inheritance by default, while inheriting from struct defaults to public inheritance.

3. Union Union

3.1 Definitions

A union (also known as a common body) is a special form of variable that is defined using the keyword Union, and its declaration and variable definitions are very similar to the structure. The form is:

Union Union name

{

Data type member name;

Data type member name;

...

} variable name;

A union represents a number of variables that share a single memory location , saving different data types and varying lengths of variables at different times . In union, all union members share a space and only the value of one of the member variables can be stored at the same time.

3.2 Federated Memory allocation

The size of the union is the maximum value of all the variables inside it, and the memory is aligned by an integer multiple of the type's maximum value .

Union A Union B Union C Union d{{{ {Charc[Ten];Charc[Ten];Charc[Ten];CharC;CharCC1;intIDoubleDinti;}               U1;                }U2;                     }U3; DoubleD; }u4;

Union A: First allocates 10 bytes according to Char C[10], then aligns with 1 bytes of char, eventually sizeof (u1) = 10;
Union B: First allocates 10 bytes according to Char C[10] and then aligns 4 bytes of int, eventually sizeof (u2) = 12; (The smallest number that is greater than or equal to 10 and divisible by 4, or 12)

Union C: First allocates 10 bytes according to Char C[10] and then aligns 8 bytes according to Doube, eventually sizeof (U3) = 16, (the smallest number greater than or equal to 10 and divisible by 8, or 16)

Union D: Allocates 8 bytes According to a double, eventually sizeof (U4) = 8;

3.3 Applications

In a C + + program, when multiple basic data types or composite data structures occupy the same piece of memory, we use a union; When multiple types, multiple objects, and many things take only one (we call them "N-Select 1"), we can also use a consortium to exploit its strengths.

Union Myun {struct{intXintYintZ;} U intK;} A intMain () {a.u.x=4; A.u.y=5; A.u.z=6; A.K=0; printf ("%d%d%d\n", a.u.x,a.u.y,a.u.z);return 0;}

The Union type is the shared memory, with the size of the largest structure as its own, so that the structure of Myun contains the structure of U, and the size is equal to the size of the structure of U, in memory in the order of the Declaration of X, Y, z from low to High, and then assign value, in memory, The position of the x is placed 4,y position placed 5,z position 6, now the K assignment, the assignment to K because it is the Union, to share memory, so from the beginning of the Union of the first address, the position of the first address is actually x position, so that the original memory x position is replaced by the value assigned by K, It becomes 0, this time to print, just look at the memory in the line, x position is K position is 0, and y,z position of the value has not changed, so should be 0,5,6.

4. Differences in structure and union:

1) Unions and structs are composed of a number of different data type members, but at any one time, the union only holds a selected member, and all members of the struct exist.

2) for the different member assignments of the Union, the other members will be rewritten, the original member value will not exist, and the structure of the different members of the assignment is not affected.

Struct struct and union 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.