[解决] struct变量和sizeof(变量)之间的差异 [英] [Solved] differences between struct variable and sizeof(variable)

查看:61
本文介绍了[解决] struct变量和sizeof(变量)之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VC ++中,我在程序中编写了结构变量:



In VC++, I have coded the structure variable in the program:

typedef struct NetCfgPacket // 81 bytes
{
char    stx;
char    cmd;
char    mac[6];
char    wantype;
char    ip[4];
char    gateway[4];
char    netmask[4];
char    dns[4];
char    devicename[32];
char    modbusviewip[4];
short   modbusviewport;
char    telnet;
char    ssh;
char    ftp;
char    web;
char    lan;
char    bridge;
char    lanip[4];
char    lanmask[4];
char    wifi;
char    ports;
char    modeltype;
char    etx;
} RP_N ;





这些变量的每个长度之和为81个字节。但是,当我计算sizeof(NetCfgPacket)的值时,它的长度为82个字节。

由于我期望的长度和'sizeof'函数之间存在这种差异,因此它会产生非常严重的问题。一些套接字程序的通信。

即使我没有检查由上面结构变量产生的缓冲区的一个字节,缓冲区大小与sizeof(NetCfgPacket)的大小相同(= 82)。



1.我不知道是什么造成了这种差异。

2.请让我知道解决方案。



谢谢



我尝试了什么:



经过一个多小时的检查,我发现了它。



The sum of each length of these variables is 81 bytes. But, when I calculated the value of the sizeof(NetCfgPacket), this has length of 82 bytes.
Because of this difference between my expecting length and 'sizeof' function, it makes very serious problem to the communications of some socket programs.
Even though I do not check one byte one byte of the buffer made by above structure variable, the buffer size is the same size(= 82) of sizeof (NetCfgPacket).

1. I don't know what makes this difference.
2. Please let me know the solution of this.

Thank you

What I have tried:

After more one hour inspection, I found it.

推荐答案

这是由struct成员的对齐提供的。您可以使用 [ ^ ] pragma以确保您的结构中没有填充字节:

This is sourced by the alignment of struct members. You can use the pack[^] pragma to ensure that there are no fill bytes in your structure:
// Push current setting and pack to one byte boundary
 #pragma pack(push, 1)
typedef struct NetCfgPacket // 81 bytes
{
char stx;
// ...
} RP_N;
// Restore previous alignment
 #pragma pack(pop)


这篇关于[解决] struct变量和sizeof(变量)之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆