C + + Union memory

Source: Internet
Author: User

See an example:

#include <iostream>#include<stdio.h>using namespacestd;union A {intA; struct {         Shortb;  ShortC; };};intMain () {A s; S.A.=0x12345678; printf ("%x%x", s.b, S.C); return 0;}

Output Result:

5678 1234

Why is that so?

Because a is union, the format that is stored in memory is:

High address------------> Low address

12 34 56 78

00010010 00110100 01010110 01111000

S.B occupies a low address of two bytes

S.C occupies a high address of two bytes

So:

s.b = 5678

S.C = 1234

To prove it, and to see more clearly, look at the program below.

#include <iostream>#include<stdio.h>using namespacestd;union A {intA; struct {         Shortb;  ShortC; };};intMain () {A s; S.A.=0x12345678; printf ("B =%x; c =%x\n", s.b, S.C); printf ("&a =%x; &b =%x; &c =%x\n", &AMP;S.A, &s.b, &S.C); return 0;}

Results:

5678 1234&a = 28ff1c; &b = 28ff1c; &c = 28ff1e

Isn't it obvious?

C + + Union memory

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.