I am learning C and have a question about structs.
I have a
struct myStruct {
    char member1[16];
    char member2[10];
    char member3[4];
};
This should take at least 30 bytes of memory to store. Would it be possible to copy all of this data into the variable char foo[30]? What would be the syntax?
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);
                        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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With