[英]strcpy doesn't work on the same size arrays
When I try to assign value of one string to other using strcpy
runtime error occurs. 当我尝试使用
strcpy
运行时将一个字符串的值分配给其他字符串时,发生错误。 Below the code: 代码下方:
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;
}
Error is: 错误是:
Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted
If I set the size of str2 equal to 6 or more program works well. 如果我将str2的大小设置为等于或大于6,则程序运行良好。 What is a problem here?
这里有什么问题?
strcpy
operates on zero-terminated strings. strcpy
对零终止字符串进行操作。 Your char arrays don't have terminating zero bytes. 您的char数组没有结尾的零字节。
If it's working when you declare the arrays as [6]
it's just by accident. 如果在将数组声明为
[6]
那只是偶然。
Function strcpy();
函数
strcpy();
expects nul \\0
terminated string. 期望nul
\\0
终止的字符串。 str[]
is not nul \\0
terminated. str[]
不是nul \\0
终止。
Because you are printing array char by char in your code, you can rectify code as suggested by @ Karoly Horvath using memcpy instead of strcpy. 因为您要在代码中逐字符打印数组char,所以可以按照@ Karoly Horvath的建议使用memcpy而不是strcpy纠正代码。
void * memcpy ( void * destination, const void * source, size_t count ); void * memcpy(void *目标,const void *源,size_t count);
memcpy(str2, str, sizeof(str));
It is very risky to use string operations without forming null-terminated strings. 使用字符串操作而不形成以null终止的字符串非常危险。
Here, strcpy() expects a null terminated string to be copied to a string which also has to be null terminated. 在这里,strcpy()期望将以空终止的字符串复制到也必须以空终止的字符串。
Therefore you must use: 因此,您必须使用:
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.