How to determine the size of an unnamed structure?

I am looking for a way to determine the size of an unnamed structure because I want to explicitly calculate the padding.

I have a set of structures that share a common layout

struct Packet { uint8_t AllocatorDebugInfo[ALLOC_SIZE /* constant across all structs */ ]; /* OPTIONAL */ uint8_t Padding[ /* Needs to be determined */ ]; uint8_t Header[HEADER_SIZE /* dependent on packet type */ ]; uint8_t Payload[PAYLOAD_SIZE /* constant across all structs*/ ]; }; 

I have the following requirements:

  • I wrote a special dispenser that has debug information before the package.
  • I want plug-in header types, while preserving the payload in all types of package layouts.

I am trying to calculate the size of the header as shown in the code below:

 typedef union { struct { /* opaque */ } SmallHeader; struct { /* opaque */ } MedHeader; struct { /* opaque */ } LargeHeader; } HeaderSizes; HeaderSizes *p; enum { SMALL_PADDING = sizeof(HeaderSizes) - sizeof(p->SmallHeader)) }; 

Unfortunately, the memory is tight, and I am looking for ways to avoid the global pointer.

EDIT:

Trying to figure out an additional complement like this is apparently a very bad idea. This only works as long as you are aware of the fact that the largest structure will have more indentation than expected (zero).

 enum { LARGE_PADDING = sizeof (HeaderSizes) - sizeof ((HeaderSizes*)0->LargeHeader) }; struct LargePacket { uint8_t AllocDebug[ALLOC_SIZE]; uint8_t Padding[ LARGE_PADDING ]; /* will evaluate to 0 -- struct size 1 */ uint8_t Payload[ PAYLOAD_SIZE ]; /* off by 1 */ }; 
+6
source share
1 answer

The sizeof statement does not need a valid instance to return the size. He just needs an expression that evaluates to the correct type. Although this is a bit hacky, you can use NULL for HeaderSizes* .

 sizeof(((HeaderSizes*)NULL)->SmallHeader) 

Since this does not dereference the null pointer, but is a syntactic construction, this is completely true and gives the correct result. For example, in the example below.

http://ideone.com/QKTOdP

+7
source

All Articles