2 alechy alechy 于 2014.03.19 09:50 提问

C++ linux Typedef 定义数组大小判断

头文件内定义了:
typedef struct {
unsigned char headtag;
unsigned int ipacket;
unsigned short packetLen;
unsigned short checkcode;
} tagUDPHead;

cpp 文件里面:
159 cout<<"tagUDPHead:"<<sizeof(tagUDPHead)<<endl;
(gdb) n
tagUDPHead:12
(gdb) p sizeof(unsigned char)
$1 = 1
(gdb) p sizeof(unsigned int)
$2 = 4
(gdb) p sizeof(unsigned short)
$3 = 2

怎么加起来应该是9,为什么打印结果是12呢?

我继续修改cpp,下面是GDB的显示:
168 cout<<"tagUDPHead1:"<<sizeof(tagUDPHead1)<<endl;
(gdb) l 158
153 m_SocketID = -1;
154 }
155 }
156
157 struct tagUDPHead1 {
158 unsigned char headtag;
159 unsigned int ipacket;
160 unsigned short packetLen;
161 unsigned short checkcode;
162 } ;
(gdb) n
tagUDPHead1:12
169 cout<<"headtag:"<<sizeof(a.headtag)<<endl;
(gdb)

headtag:1
170 cout<<"ipacket:"<<sizeof(a.ipacket)<<endl;
(gdb)

ipacket:4
171 cout<<"packetLen:"<<sizeof(a.packetLen)<<endl;
(gdb)

packetLen:2
172 cout<<"checkcode:"<<sizeof(a.checkcode)<<endl;
(gdb)

checkcode:2

1个回答

alechy
alechy   2014.03.19 10:06

自己弄明白了,原来是linux字节对对齐问题:
详细:http://blog.chinaunix.net/uid-26544753-id-3364725.html

只要在定义前加一个
#pragma pack(1)
typedef struct
{
unsigned char headtag; //'#'
unsigned long ipacket; //当前包号,用以确认包的连续性及丢包情况,每天起始包从0开始
unsigned short packetLen; //当前UDP包的长度
unsigned short checkcode; //对除包头外的内容的CRC16校验
} tagUDPHead;
#pragma pack()

就OK了.

Csdn user default icon
上传中...
上传图片
插入图片