#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "conio.h"
typedef struct UploadUserInfo
{
char BirthDate[8];
char nation[3];
char address[70];
}upload_element;
char s_nation[3]="gg";
char s_address[70]="ddddd";
char s_birthday[8]={0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38};
void main()
{
upload_element s1,s2;
memset(&s1,0,sizeof(upload_element));
memset(&s2,0,sizeof(upload_element));
strcpy(s1.address,s_address);
strcpy(s1.nation,s_nation);
strcpy(s1.BirthDate,s_birthday);
printf("\n%s\n",s1.address);
printf("\n%s\n",s1.BirthDate);
printf("\n%s\n",s1.nation);
s2=s1;
printf("\n---------%s-------%s--------%s------\n",s2.address,s2.BirthDate,s2.nation);
}
输出结果:
ddddd
12345678
-----------ddddd-------------12345678--------------------------------------
结论:s1.nation和s2.nation都没有值。
为什么会出现这种情况:
因为结构体中的成员变量的内存分配是连续的,是相邻的,上述的代码中给BirthDate[8]赋值时,并没有结束符'\n',而代码中又先给成员nation赋值,再给BirthDate赋值,当给BirthDate赋值时,由于没有结束符,当到了第八个字节时没有停止,继续赋值,而由于nation在结构体中内存挨着BirthDate,又在其之后,因此被覆盖,导致无值。