C++ strcpy()的用法

#include <iostream>int main(){    using namespace std;    char a[3];    strcpy(a,"affd sfasdfsdf");    cout << a[5] << endl;    cout << a << endl;
}

这里的输出结果居然是:
s
affd sfasdfsdf
奇怪,a的长度明明是3,为什么会有这样的输出结果呢?


Qyouu
浏览 641回答 1
1回答

忽然笑

关于char *strcpy( char *dest, const char *src );,去看一下cppreference里的描述:Copies the null-terminated byte string pointed to by src, includingthe null terminator, to the character array whose first element ispointed to by dest. The behavior is undefined if the dest array isnot large enough. The behavior is undefined if the strings overlap.The behavior is undefined if either dest is not a pointer to acharacter array or src is not a pointer to a null-terminated bytestring.重点是The behavior is undefined if the dest array is not large enough,意思说如果你的a没有足够的空间放下你的字符串字面量,编译器可以随心所欲的给出任何结果,也不需要给出任何的报错(当然编译器也可以给出貌似正确的结果就像你给出的stdout那样)。另外,个人的观点是能用std::string的时候(不需要考虑兼容),就尽量不要用char *,费心费力还容易写错。
打开App,查看更多内容
随时随地看视频慕课网APP