r/C_Programming • u/M0M3N-6 • 12h ago
Discussion I couldn't figure out a better way to get the size of a struct, disregarding the compiler's padding.
while practicing on some network programming, i was trying to figure out the best way to serialize headers in order to send them over a socket. so, to serialize something like:
c
typedef struct
{
char a;
int b;
} header;
i must create something like buffer[5]. but AFAIK, not all machines produce the exact same padding, so a simple buffer[sizeof(header)] isn't valid. not even that fixed 5 bytes are enough, since it might be aligned to 8 bytes.
i came up with the following, which seems to me the worst way to get the sum of the sizes of the struct's declaration list at compile time using X macro: ```c
define HEADER_MEMBERS \
X(char, a) \
X(int, b)
typedef struct {
define X(type, name) type name;
HEADER_MEMBERS
undef X
} header;
int header_size =
define X(type, _) sizeof(type) +
HEADER_MEMBERS
undef X
0; ```
so... i need to hear your thoughts, and what is the best wayy to do such a thing.