简体   繁体   English

C ++计算大小

[英]C++ calculating size

Consider a packet which consists of header followed by multiple values. 考虑一个包,该包由报头和多个值组成。 If hdr points to the packet header and lastValue points to last value in the packet. 如果hdr指向数据包头,并且lastValue指向数据包中的最后一个值。 can you please explain me the following code: 能否请您向我解释以下代码:

size_t  calcSize   = (lastValue - (char *)hdr); 

What size does calcSize denote of the packet. calcSize表示数据包的大小。 In other words what are the start and end locations that is being considered for this size. 换句话说,此大小考虑的开始和结束位置是什么。 Thanks, 谢谢,

calcSize将是数据包中的字节数。

In this case this kind of arithmetic makes not much sense. 在这种情况下,这种算法没有多大意义。 This is because your last entity/value in a packet may be for example 32bit(4byte) and substracting pointer to a header from it makes no sense - better is to use pointer to first byte after the packet in your substraction 这是因为数据包中的最后一个实体/值可能是例如32bit(4byte),并且从该数据包减去指向报头的指针没有任何意义-最好在减去数据包后使用指向数据包后的第一个字节的指针

int packetLen = (char*)firstByteAfterPacketPtr - (char*)headerPtr;  

      7   8   9  10  11  12  13  14  15  16   17  <-- example byte index
    +---+---+---+---+---+---+---+---+---+---+
... |   header  |   v1  |v2 |    value3     |......
    +---+---+---+---+---+---+---+---+---+---+
      ^                       ^                ^
      headerPtr               lastValPtr       firstByteAfterPacketPtr

Your arithmetic would give: 您的算术将给出:

 int packetLen = (char*)lastVarPtr - (char*)headerPtr; // 13-7=6 wrong

Correct is: 正确的是:

 int packetLen = (char*)firstByteAfterPacketPtr - (char*)headerPtr; // 17-7=10 ok

Be careful about pointer arithmetic - in case of (char*) you get byte difference, in case of pointers to 16bit eitities you get diff expressed in number of 16bit entities etc.. 注意指针算术-在(char *)的情况下,您会得到字节差,在指针到16bit的情况下,会以16bit实体的数量等表示差异。

这是指针算法: (lastValue - hdr)表示两个char指针之间的差,这意味着它们之间的char大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM