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[5];
uint8_t pad1;
uint8_t lastName[4];
uint8_t pad2;
uint8_t dateOfBirth[7];
uint8_t pad3;
uint8_t genre;
uint8_t pad4;
uint8_t car[4];
uint8_t pad5;
uint8_t phone[4];
uint8_t pad6;
}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
return 0;
}
uint8_t lastName[3];
means lastName contains 1 or 2 characters then the \0, not 3 characters0
-terminatedchar
-arrays.byte
, or to be more precise aunit8_t
.memcpy(&foo, buffer, sizeof foo);
Easy to code right, review and maintain.