- 共用体中辨析多个字节变量如何存储在内存中?详见union.c
Last active
November 8, 2017 01:24
-
-
Save bllli/78c5cd19febc79bbbfaa6ddb1e805269 to your computer and use it in GitHub Desktop.
给大宝贝儿写的C语言练习题
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int main(){ | |
// 输出各种类型的长度 | |
printf("sizeof(short): %ld\n", sizeof(short)); | |
printf("sizeof(int): %ld\n", sizeof(int)); | |
printf("sizeof(long): %ld\n", sizeof(long)); | |
printf("sizeof(char): %ld\n", sizeof(char)); | |
union{ | |
short i[2]; | |
long k; | |
char c[4]; | |
}r, *s = &r; | |
printf("sizeof(r): %ld\n", sizeof(r)); | |
// 输出共用体变量内部变量的地址 | |
printf("i[0]@ %p\n", &r.i[0]); | |
printf("i[1]@ %p\n", &r.i[1]); | |
printf("k @ %p\n", &r.k); | |
printf("c[0]@ %p\n", &r.c[0]); | |
printf("c[1]@ %p\n", &r.c[1]); | |
printf("c[2]@ %p\n", &r.c[2]); | |
printf("c[3]@ %p\n", &r.c[3]); | |
// 可以看出i[0]、k、c[0]共用同一个地址 | |
s -> i[0] = 0x39; | |
s -> i[1] = 0x38; | |
printf("s->c[0]: %x\n", s -> c[0]); | |
// i[0] 与 c[0] c[1] 占用相同的两个字节 | |
// i[1] 与 c[2] c[3] 占用相同的两个字节 | |
s -> c[0] = 0x80; | |
s -> c[1] = 0x81; | |
s -> c[2] = 0x82; | |
s -> c[3] = 0x83; | |
printf("s->i[0]: %hx\n", s -> i[0]); | |
// 输出 8180 | |
printf("s->i[1]: %hx\n", s -> i[1]); | |
// 输出 8382 | |
// 说明地址高的(c[1]比c[0]地址号大)在高位,地址低的在低位 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment