Search code examples
cstructmemcpy

memcpy error on struct


I'm getting the following error with memcpy. It doesn't give compilation error but doesn't give the result I would imagine. I've never used memcpy before so I'm sure I'm making a simple mistake. I've looked around previous questions but couldn't find one with structures. I can use memcpy on independent variables but just not on structs.

If someone can point out my mistake it'll be great.

#include <stdio.h>
#include <string.h>


int main() {
 struct st{
 char c1[12];
 char c2[32];
 char c3[3];
 char c4[7];
 char c5[13];
 char c6[5];
 char c7[10];
 };
 struct st s;
 char s1[] = "part number";
 char s2[] = "j9uijd9d09fj";
 char s3[] = "abc";
 char s4[] = "seven";
 char s5[] = "aaaaaaaa";
 char s6[] = "ptype";
 char s7[] = "user";
 memcpy(s.c1,s1,sizeof(s.c1));
 memcpy(s.c2,s2,sizeof(s.c2));
 memcpy(s.c3,s3,sizeof(s.c3));
 memcpy(s.c4,s4,sizeof(s.c4));
 memcpy(s.c5,s5,sizeof(s.c5));
 memcpy(s.c6,s6,sizeof(s.c6));
 memcpy(s.c7,s7,sizeof(s.c7));
 printf("%s\n",s.c1);
 printf("%s\n",s.c2);
 printf("%s\n",s.c3);
 printf("%s\n",s.c4);
 printf("%s\n",s.c5);
 printf("%s\n",s.c6);
 printf("%s\n",s.c7);
 return 0;
}

OUTPUT I'm getting :

part number
j9uijd9d09fj
abcseven
seven
aaaaaaaa
ptypeuser
user

Thanks!!!


Solution

  • Change the size of c3 in your struct to 4 and c6 to 6 to allow for the NULL terminator.

    struct st{
        char c1[12];
        char c2[32];
        char c3[4]; /* putting 'abc' which is 4 chars */
        char c4[7];
        char c5[13];
        char c6[6]; /* putting 'ptype' which is 6 chars */
        char c7[10];
    };