strcpy 不适用于相同大小的数组
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个以