- Unions in C language:
- Pseudocode says:
union 类型名{
数据类型1 成员1;
数据类型2 成员2;
数据类型3 成员3;
.
.
.
数据类型n 成员n;
};
- Common features:
- 1. All members share the same memory space
- 2. The first address of all members is the same;
- 3. The size depends on the largest member in the union;
- Supplementary knowledge:
共用体清0
: Use the memset function, the header file is string.h
;
- memset function format:
void *memset(void *s,int c,size_t n);
#include<stdio.h>
#include<string.h>
union Test{
char a;
short b;
int c;
long d;
long long e;
};
int main(int argc, const char *argv[]){
union Test k;
printf("sizeof(k) = %lld\n",sizeof(k));
memset(&k,0,sizeof(k));
k.a = 220;
printf("k.b = %d\n",k.b);
printf("k.c = %d\n",k.c);
printf("k.d = %ld\n",k.d);
printf("k.e = %lld\n",k.e);
puts("--------------------------");
printf("&k.a = %p\n",&k.a);
printf("&k.b = %p\n",&k.b);
printf("&k.c = %p\n",&k.c);
printf("&k.d = %p\n",&k.d);
printf("&k.e = %p\n",&k.e);
return 0;
}
sizeof(k) = 8
k.b = 220
k.c = 220
k.d = 220
k.e = 220
--------------------------
&k.a = 000000000062FE10
&k.b = 000000000062FE10
&k.c = 000000000062FE10
&k.d = 000000000062FE10
&k.e = 000000000062FE10
- Instance requirements:
- Use a union (union) to determine whether the storage mode of the PC is big-endian storage or little-endian storage;
- For details on the storage methods of big endian and little endian, see my original blog
链接
:
https:
#include <stdio.h>
union Test{
char a;
int b;
};
int main(int argc, const char *argv[]){
union Test k;
k.b = 0x12345678;
if (0x78 == k.a) {
printf("该PC是小端存储\n");
} else {
printf("该PC是大端存储\n");
}
return 0;
}
该PC是小端存储