Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C ever pad a struct before the first element?

Tags:

c

Consider an arbitrary struct where the C compiler will perform padding

struct node {
  enum type;
  size_t num_children;
  void** nodes;
};

Will C ever perform padding before the first element? I ask this as I need to do some funky things with void* and require that

void* a = node->nodes[0];
enum type t = *(enum type*)(a);

will always be evaluated correctly. I'm aware that I can force no padding but would rather not.

like image 864
washcloth Avatar asked Apr 30 '26 14:04

washcloth


1 Answers

Will C ever perform padding before the first element?

No. This is explicitly prohibited in the C standard:

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

(emphasis mine).

like image 168
P.P Avatar answered May 02 '26 07:05

P.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!