1

suppose I have the following struct declaration

struct m27
{
uint64_t head ;
int vp_array[500] ;
float lpx[500] ;
s_ent ent[500*plno] ;
uint32_t crc ;
};

prior to writing to disk or transmitting over the network I wish to compute the crc value. I need to get the number of bytes excluding the last field The best that I have come up with is

((char*) &(((m27*) secspec)->crc)) - ((char*)&(((m27*) secspec)->head))

where secspec is a void pointer that points to a struct of type m27 This seems rather cumbersome and error prone however. The initially obvious of sizeof(m27)-sizeof(uint32_t) does not work as it yields the wrong answer due to padding. Is there a better way?

camelccc
  • 2,847
  • 8
  • 26
  • 52
  • 3
    The `offsetof` macro `size_t offsetof(structName, memberName);` returns the offset in bytes of the specified member from the beginning of its parent data structure. It is undefined for bit fields (MSVC). – Weather Vane Dec 05 '19 at 19:07
  • ...but this would still include any padding after the previous member. – Weather Vane Dec 05 '19 at 19:15
  • As a simple solution you could use `#pragma pack(1)` or `__attribute__((packed))` to force compiler to use 1 byte packaging, that will ensure that `sizeof(m7)` returns the sum of the size of its members. Then your answer will be `sizeof(m27)-sizeof(uint32_t)` – Matias Moreyra Dec 05 '19 at 19:27

0 Answers0