www.zhishiwu.com
结构体定义:[cpp]<span
style=font-size:18px>struct
a{
int
xx:4
int
yy:4
}</span>
结构体初始化:方式一:[cpp]<span
style=font-size:18px>struct
a
aa
={
xx:2,
yy:3
}</span>
www.zhishiwu.com
方式二:[cpp]<span
style=font-size:18px>struct
a
cc
={
.xx=6,
.yy=1,
}</span>
方式三:[cpp]<span
style=font-size:18px>struct
a
dd={4,2}</span>
在定义中,可以限制变量的位的作用域,比如上面的:int
xx:4这表明xx的有效域只有4位,也就是能给他赋值的最大值为15,如果超过这个值,编译器就会报错:warning:
overflow
in
implicit
constant
conversion。在这里如果你给xx赋值为15,如:[cpp]<span
style=font-size:18px>struct
a
cc
={
.xx=15,
.yy=1,
}</span>
www.zhishiwu.com
然后输出:[cpp]<span
style=font-size:18px>printf(cc.xx
=
%d/n,cc.xx)</span>
结果会是:-1因为这里定义的xx为int
型,15的二进制位1111,最高位为1,表示为负数,所以取反加1后为0001。所以是-1。这种位域 *** 作的好处是当你不需要用到你定义的类型的长度时,可以加位域 *** 作以节省内存空间。引出的其他问题这里用sizeof(struct
a)得到的是4,如果不加位域限制则是8,至于为什么是4呢?4bit+4bit应该刚好是1byte啊,应该是1才对啊。这是因为我是在linux下编译执行的,而在linux对内存分配最小值为类型值的一半。(我在linux下做了实验)如下我定义了一个结构体:[cpp]<span
style=font-size:18px>struct
a{
short
int
xx:2
short
int
yy:2
}bb</span>
如上,我定义二个short
int类型值,short
int在32位linux下为2字节,这里二个相加不足一字节,但是输出sizeof(struct
a)的值为2。不足一字节系统自动补满一字节。[html]<span
style=font-size:18px>struct
a{
short
int
xx:9
short
int
yy:2
}bb</span>
www.zhishiwu.com
这个输出也是2。xx超过一字节,但是9+2=11,还没有超过16(2字节),我猜系统将xx超过的那1bit分到了yy那1bit里面了。[cpp]<span
style=font-size:18px>struct
a{
short
int
xx:9
short
int
yy:9
}bb</span>
这个输出是4。9+9=18,超过了16,系统各分配了2字节给xx和yy。作者
linuxblack125125
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)