Copy multiple structs into a buffer using memcpy in c -


  1. i have several structs (of u8 fields) want convert buffer, best way?

    struct struct_a a; struct struct_b b; u8 buffer[64]; u8 *next_pos;  os_memcpy(buffer, &a, sizeof(struct_a));  next_pos = buffer + sizeof(struct_a)/sizeof(u8);  os_memcpy(next_pos, &b, sizeof(struct_b)); 
  2. is best way calculate overall length of buffer?

    buffer_len = (sizeof(struct_a) + sizeof(struct_b) + ... )/sizeof(u8); 

thanks

i assume u8 means unsigned 8 bits. hence, sizeof(u8) equals 1. can write:

os_memcpy(&buffer[sizeof(struct_a)], &b, sizeof(struct_b)); 

for second question, except dividing 1 useless, it's fine way compute len of buffer.

i'm not big fan of buffer + sizeof(struct_a) it's good.

edit: also, when doing kind of stuff, if size of elements of buffer not 1, cast buffer equivalent of u8. way, don't have divide size of elements of buffer.


Comments

Popular posts from this blog

iphone - Three second countdown in cocos2d -

hyperlink - how to do url routing in php -

c - Avoiding Extra Malloc in Linked List (node->next = NULL) -