Accessing Struct members using memcpy in C -


i have structure :

struct x{ int a; int b; int c; } 

i have array :

unsigned char bytes[8]; bytes[0] = 1 bytes[1] = 128 bytes[2] = 0 bytes[3] = 0 bytes[4] = 255 bytes[5] = 255 bytes[6] = 0 bytes[7] = 0 

i want copy bytes[0] bytes[3] in struct element "a", bytes[4] bytes[6] in struct element "b" , bytes[7] in struct element "c". have use memcpy. how can that? please help.

my try :

struct x test; memcpy( &test.a, bytes, 4); memcpy( &test.b, bytes + 4, 3); memcpy( &test.c, bytes + 7, 1); 

but showing different results every time run it.

in code don't initialize test. ends happening is:

  • the fields have undefined ("garbage") data
  • you partially write fields

for example when memcpy( &test.b, bytes + 4, 3); if have sizeof(int) == 4 (likely) end writing 3 bytes leaving 1 byte undefined.

try easy initializing object:

struct x test = {0}; 

Popular posts from this blog