[英]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.