Copy struct into char array

The size of struct myStruct is sizeof(struct myStruct) and nothing else. It'll be at least 30, but it could be any larger value.

You can do this:

char foo[sizeof(struct myStruct)];

struct myStruct x; /* populate */

memcpy(foo, &x, sizeof x);

You can't just directly copy the whole thing, because the compiler may arbitrarily decide how to pad/pack this structure. You'll need three memcpy calls:

struct myStruct s;
// initialize s
memcpy(foo,                                       s.member1, sizeof s.member1);
memcpy(foo + sizeof s.member1,                    s.member2, sizeof s.member2);
memcpy(foo + sizeof s.member1 + sizeof s.member2, s.member3, sizeof s.member3);

Tags:

C

Struct