union [tag]
{
member definition;
member definition;
...
member definition;
[variables];
union test
{
int i;
float f;
double d;
char str[20];
} data;
#
#
union test
{
int i;
float f;
double d;
char str[20];
};
int main( )
{
union test data;
printf( "data size : %d\n", sizeof(data));
return 0;
}
/*beginner/union/union2.c*/
#
#
union Data {
int i;
float f;
char str[20];
};
int main()
{
union Data data;
data.i = 123;
data.f = 456.0;
strcpy(data.str, "Hello World");
printf("data.i : %d\n", data.i);
printf("data.f : %f\n", data.f);
printf("data.str : %s\n", data.str);
return 0;
}
从结果上来看,what are you弄啥嘞,感觉什么跟什么呀,只有最后的字符串是正确的,这也就间接证明了共用体使用相同的存储空间,其他类型的赋值会破坏原先的赋值,正常情况下只有最后一次的赋值才会保证正确结果。
/*beginner/union/union3.c*/
#
#
union Data {
int i;
float f;
char str[20];
};
int main()
{
union Data data;
data.i = 123;
printf("data.i : %d\n", data.i);
data.f = 456.0;
printf("data.f : %f\n", data.f);
strcpy(data.str, "Hello World");
printf("data.str : %s\n", data.str);
return 0;
}
再次运行,可以看到结果就按照预想的进行了。
#beginner/union/Makefile
ALL : union1 union2 union3
union1: union1.c
gcc -o union1 union1.c
union2: union2.c
gcc -o union2 union2.c
union3: union3.c
gcc -o union3 union3.c
clean :
clean:
rm -f union1 union2 union3
$ ./union2
data.i : 1819043144
data.f : 1143139122437582505939828736.000000
data.str : Hello World
$ ./union3
data.i : 123
data.f : 456.000000
data.str : Hello World
typedef struct
{
unsigned int red;
unsigned int green;
unsigned int yellow;
} TrafficLight;
此时如果看一下TrafficLight结构体的大小,应该是12个字节
typedef struct
{
type name : width;
}
typedef struct
{
unsigned int red : 1;
unsigned int green : 1;
unsigned int yellow : 1;
} TrafficLight1;
/*beginner/struct/struct6.c*/
#
int main()
{
typedef struct
{
unsigned int red;
unsigned int green;
unsigned int yellow;
} TrafficLight;
TrafficLight trafficlight;
printf("The size of TrafficLight %d\n", sizeof(trafficlight));
typedef struct
{
unsigned int red : 1;
unsigned int green : 1;
unsigned int yellow : 1;
} TrafficLight1;
TrafficLight1 trafficlight1;
printf("The size of TrafficLight1 %d\n", sizeof(trafficlight1));
return 0;
}
#beginner/struct/Makefile
struct6: struct6.c
gcc -o struct6 struct6.c
运行输出如下:
$ ./struct6
The size of TrafficLight 12
The size of TrafficLight1 4
warning: implicit truncation from ‘int’ to bit-field changes value from 2 to 0 [-Wbitfield-constant-conversion]
-END-
免责声明:整理文章为传播相关技术,版权归原作者所有,如有侵权,请联系删除