I have the following code
struct Info { int age; char name[5]; }
char buffer[20];
Info i;
i.age = 10;
sprintf(i.name, "Case");
strncpy(buffer+5, (char*)&i, sizeof(Info));
Now I want to recover the record
Info j;
strncpy((char*)&j, buffer+5, sizeof(Info));
printf("%d %s", j.age, j.name);
However this prints empty string for name. I’m not sure what I am doing wrong.
There are two problems with your copying mechanism:
sizeof(Info)is 5. That’s definitely not the case.strncpy, which is for strings.Infois not a string, so you need to usememcpy.The following will work:
There’s also another problem;
name[5]is not big enough to hold"Casey", as that’s 6 characters once you’ve accounted for the null terminator.