[英]strcpy doesn't work on the same size arrays
當我嘗試使用strcpy
運行時將一個字符串的值分配給其他字符串時,發生錯誤。 代碼下方:
int main (int argc, char **argv)
{
char str[5];
char str2[5];//if set size of str2 equal to 6, no error occurs
str[0] = 'a';
str[1] = 'b';
str[2] = 'c';
str[3] = 'd';
str[4] = 'e';
cout<<sizeof(str)<<endl;
cout<<str[0]<<endl;
cout<<str[1]<<endl;
cout<<str[2]<<endl;
cout<<str[3]<<endl;
cout<<str[4]<<endl;
strcpy(str2,str);
cout<<sizeof(str2)<<endl;
cout<<str2[0]<<endl;
cout<<str2[1]<<endl;
cout<<str2[2]<<endl;
cout<<str2[3]<<endl;
cout<<str2[4]<<endl;
getch();
return 0;
}
錯誤是:
Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted
如果我將str2的大小設置為等於或大於6,則程序運行良好。 這里有什么問題?
strcpy
對零終止字符串進行操作。 您的char數組沒有結尾的零字節。
如果在將數組聲明為[6]
那只是偶然。
函數strcpy();
期望nul \\0
終止的字符串。 str[]
不是nul \\0
終止。
因為您要在代碼中逐字符打印數組char,所以可以按照@ Karoly Horvath的建議使用memcpy而不是strcpy糾正代碼。
void * memcpy(void *目標,const void *源,size_t count);
memcpy(str2, str, sizeof(str));
使用字符串操作而不形成以null終止的字符串非常危險。
在這里,strcpy()期望將以空終止的字符串復制到也必須以空終止的字符串。
因此,您必須使用:
char str[6];
char str2[6];
str[0] = 'a';
str[1] = 'b';
str[2] = 'c';
str[3] = 'd';
str[4] = 'e';
str[5] = '\0';
strcpy(str2,str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.