不可忽略的小问题

时间:2022-06-05 19:08:28

typedef struct tagStruct
{
    char wchar[4];
    char wchar2[5];
}TSTRUCT;

    TSTRUCT tstruct;
    strcpy(tstruct.wchar,"aaaaaaaa");
    strcpy(tstruct.wchar2,"bbbbbbbbbb");
    AnsiString str1 = tstruct.wchar;           //str1=aaaabbbbbbbbbb
    AnsiString str2 = tstruct.wchar2;         //str2=bbbbbbbbbb

wchar不是我想要的那个,What I want is “aaaa”;

wchar越界了,What I want is “bbbbb”;

正确的用法是给wchar和wchar2都扩大一个字节

typedef struct tagStruct
{
    char wchar[5];           //比要求的大了一个字节
    char wchar2[6];         //比要求的大了一个字节
}TSTRUCT;


    TSTRUCT tstruct;
    memset(&tstruct,0,sizeof(tstruct));        //一定要memset一下,否则也是错的
    strncpy(tstruct.wchar,"aaaaaaaaa",sizeof(tstruct.wchar)-1);
    strncpy(tstruct.wchar2,"bbbbbbbbb",sizeof(tstruct.wchar2)-1);
    AnsiString str1 = tstruct.wchar;             //str1 = “aaaa“
    AnsiString str2 = tstruct.wchar2;           //str2 = “bbbbb”