【发布时间】:2013-09-08 20:02:08
【问题描述】:
当我尝试使用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 或更多,程序运行良好。 这里有什么问题?
【问题讨论】:
-
即使使用 str2[6],str2[7] 也会出错。 Barmar 的答案是正确的。
-
终止字符串,或者如果它们不是字符串,使用
memcpy -
你是对的。 strcpy 不适用于数组。你的问题是什么
标签: c++ error-handling strcpy