开发者社区> 问答> 正文

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

展开
收起
a123456678 2016-03-04 17:35:46 2509 0
1 条回答
写回答
取消 提交回答
  • 只要在定义前加一个

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

    就OK了.

    2019-07-17 18:52:38
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Alibaba Cloud Linux 3 发布 立即下载
ECS系统指南之Linux系统诊断 立即下载
ECS运维指南 之 Linux系统诊断 立即下载