Copy a uint8_t array to a struct

  • A+

I have this array

uint8_t *buffer = "JOHN:DOE:010119:M:FOO:BAR"; 

and I want to copy it field by field to data structure

typedef struct{   uint8_t firstName[4];   uint8_t pad1;   uint8_t lastName[3];   uint8_t pad2;   uint8_t dateOfBirth[6];   uint8_t pad3;   uint8_t genre;   uint8_t pad4;   uint8_t car[3];   uint8_t pad4a;   uint8_t phone[3];   uint8_t pad5; }DataStructTypeDef; 

Let's say that all lengths are fixed (eg. firstName is always composed of 4 characters, lastName of 3 etc ...)

I used this approach:

DataStructTypeDef foo; memcpy((void *)&foo, (void *)buffer, sizeof(DataStructTypeDef)); 

When I try to print dateOfBirth it shows the whole array starting from 01012019 like this

int main(void) {   DataStructTypeDef foo;   memcpy((void *)&foo, (void *)buffer, sizeof(DataStructTypeDef));   printf("%s", foo.dateOfBirth); // It prints 010119:M:FOO:BAR //printf("%s", foo.dateOfBirth); // Expected value 010119 } 


Since the char array members you are copying are not null terminated, printf("%s", will not know when it has encountered the end of each string.

This can be controlled in printf by limiting the amount of characters that print...

For example:

printf("%.*s", (int)sizeof(foo.dateOfBirth), foo.dateOfBirth); 

An equivalent would be:

printf("%.6s", food.dateOfBirth); 

.* specifies the "precision" of characters you want to print. So in your case, dateOfBirth = precision/size 6.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: