The are two issues here:
1) As mentioned in comments you likely forget to include space for the ending '\0'
(i.e. NUL
in ASCII) terminator character. The %s
format specifier for printf
function expects that character string is in valid form. However nothing stops you from printing as sequence of characters, like here:
#include <stdio.h>
#include <string.h>
struct {
char a[2];
char b[2];
} buff;
char buffer1[5] = "ABCD";
int main(void)
{
memcpy(&buff, buffer1, 4);
printf("First member: %c%c\n", buff.a[0], buff.a[1]);
printf("Second member: %c%c\n", buff.b[0], buff.b[1]);
return 0;
}
2) A more serious issue is that compiler may include arbitrary padding between struct members (as well as after last member), so memcpy
may not work as expected. Instead of copying like that (as it may put bytes from array into a unused "wholes"). I would suggest individual copies of each member or maybe using offsetof()
macro.
From N1570 6.7.2.1/15
Structure and union specifiers:
There may be unnamed padding within a structure object, but not at its
beginning.
and 6.7.2.1/17
:
There may be unnamed padding at the end of a structure or union.
Hence, you should split your memcpy
into two calls, for instance:
memcpy(&buff.a, buffer1, 2); /* or replace 2 with sizeof buff.a */
memcpy(&buff.b, buffer1+2, 2);