Search code examples
cmemcpystring-literals

Copy a uint8_t array to a struct


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;
}

Solution

  • 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.