Differences between the Community and struct in C

Source: Internet
Author: User

Shared body
Construct a data type, also called a consortium
Purpose: make several different types of variables occupy a portion of memory (overwrite each other)

Struct is a type of constructed data.
Purpose: combine different types of data into a whole ------- Custom Data

The Memory Length occupied by struct variables is the total memory length occupied by each member.

The Memory Length occupied by the community variables is the Memory Length occupied by the longest members.

Which of the following can be stored in a community !!

The members that play a role in the community variables are the members of the last storage,
After new members are saved, the original members become useless!

Structure and Union have the following differences:

1. struct and union are composed of multiple members of different data types, but at any time, union only stores one selected member, and all the members of struct exist. In struct, each member occupies its own memory space and they exist at the same time. The total length of a struct variable is equal to the sum of all member lengths. In union, all Members cannot occupy their memory space at the same time, and they cannot exist at the same time. The length of the Union variable is equal to the length of the longest member.

2. Assignment of different members of the union operation will be rewritten to other members. The original value of the union operation does not exist, but the assignment of different members of struct does not affect each other.

For example:

Example:

# Include <stdio. h>

Void main ()
{
Union {
Int I;
Struct {
Char first;
Char second;
} Half;
} Number;
Number. I = 0x4241;
Printf ("% C % CN", number. Half. First, number. Half. Second );
Number. Half. First = 'a ';
Number. Half. Second = 'B ';
Printf ("% XN", number. I );
}

Output result:
AB
6261

Related Article

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.