Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy struct into char array

Tags:

c

struct

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?

like image 458
yiwei Avatar asked Oct 17 '14 17:10

yiwei


2 Answers

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);
like image 53
Carl Norum Avatar answered Nov 12 '22 08:11

Carl Norum


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);
like image 5
Kerrek SB Avatar answered Nov 12 '22 06:11

Kerrek SB