Hard to understand C code (1)

Source: Internet
Author: User
#include <stdio.h>
int main () {
	union{
		int ig[4];
		Char a[8];
	} t;
	T.ig[0] = 0x4241;
	T.IG[1] = 0x4443;
	T.IG[2] = 0x4645;
	T.IG[3] = 0x0000;
	printf ("\n%s\n", t.a);
	return 0;
}

First look at the results:

It's very nice to be here.

Try the following program:

#include <stdio.h>
int main () {
	union{
		int ig[4];
		Char a[8];
	} t;
	T.ig[0] = 0x4241;
	T.IG[1] = 0x4443;
	T.IG[2] = 0x4645;
	T.IG[3] = 0x0000;
	printf ("\n%s\n", t.a);
	printf ("%d\n", sizeof (t));
	return 0;
}
Results:

As you can see, the union length is 16, and you can infer that the int in the Union is 4 bytes and char is a byte (this is known to all C).

Try the following program:

#include <stdio.h>
int main () {
	union{
		int ig[4];
		Char a[8];
	} t;
	T.ig[0] = 0x4241;
	T.IG[1] = 0x4443;
	T.IG[2] = 0x4645;
	T.IG[3] = 0x0000;
	printf ("\n%s\n", t.a);
	printf ("%d\n", sizeof (t));
	return 0;
}

Results:

As you can see, the result is AB, because in 0x4241, 41 is stored in the low, that is, the head address of the IG array, which first outputs 0x41 (A) and then outputs 0x42 (B)

But the t.ig[1] = 0x4443 Note removed, found that the result is still ab,why? later thought, each element is 32 bits, and 0x4241 only occupy 16 bits, the back 16 is empty, so that when the second 8 digits, because no content, then stop reading, All subsequent assignments, even for other elements in the IG array, are not exported.

You can try this by using the following procedure:

#include <stdio.h>
int main () {
	union{
		int ig[4];
		Char a[8];
	} t;
	T.ig[0] = 0x44434241;
	T.IG[1] = 0x4443;
	T.IG[2] = 0x4645;
	T.IG[3] = 0x0000;
	printf ("\n%s\n", t.a);
	printf ("%d\n", sizeof (t));
	return 0;
}

Results:

Can see the completion of ig[0] After the 16, the result is ABCDCD, this time to understand.


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.