当我尝试使用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 或更多,程序运行良好。这里有什么问题?