您的位置:首页 > 编程语言 > C语言/C++

C语言 - 结构体(struct)比特字段(:) 详细解释

2015-07-18 20:39 423 查看

结构体(struct)比特字段(:) 详细解释

本文地址: http://blog.csdn.net/caroline_wendy/article/details/26722511
结构体(struct)能够使用位字段(:), 节省空间, 例如以下面代码,

结构体a中的, 第一个变量x占用1个字符, y占用2个字符, z占用33个字符(越界);

可是sizeof()自己主动补齐, 如x+y一共占用4个字节, z占用8个字节, 所以结构体占用12个字节;

当使用加法运算时, 会初始化为0;

代码:

/*
* test.cpp
*
*  Created on: 2014.05.23
*      Author: Spike
*/

/*eclipse cdt, gcc 4.8.1*/

#include <iostream>
#include <stdio.h>

using namespace std;

struct a {
int x:1;
int y:2;
int z:33;
};

int main()
{
a d;
cout << &d << std::endl;
d.z = d.x + d.y;
printf("%d %d %d %d\n", d.x, d.y, d.z, sizeof(d));

return 0;
}


输出:

0x22fed4
0 0 0 12


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: