I receive datagrams through a network and I would like to copy the data to a struct with the appropirate fields (corresponding to the format of the message). There are many different types of datagrams (with different fields and size). Here is a simplified version (in reality the fields are always arrays of chars):
struct dg_a
{
char id[2];
char time[4];
char flags;
char end;
};
struct dg_a data;
memcpy(&data, buffer, offsetof(struct dg_a, end));
Currently I add a dummy field called end
to the end of the struct so that I can use offsetof
to determine how many bytes to copy.
Is there a better and less error-prone way to do this? I was looking for something more portable than putting __attribute__((packed))
and using sizeof
.
--
EDIT
Several people in the comments had stated that my approach is bad, but so far nobody has presented a reason why this is. Since struct members are char
, there are no trap representations and no paddings between the members (guaranteed by the standard).