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,为什么会有这样的输出结果呢?

阅读 4.6k
3 个回答

关于char *strcpy( char *dest, const char *src );,去看一下cppreference里的描述:

Copies the null-terminated byte string pointed to by src, including
the null terminator, to the character array whose first element is
pointed to by dest. The behavior is undefined if the dest array is
not large enough. The behavior is undefined if the strings overlap.
The behavior is undefined if either dest is not a pointer to a
character array or src is not a pointer to a null-terminated byte
string.

重点是The behavior is undefined if the dest array is not large enough,意思说如果你的a没有足够的空间放下你的字符串字面量,编译器可以随心所欲的给出任何结果,也不需要给出任何的报错(当然编译器也可以给出貌似正确的结果就像你给出的stdout那样)。

另外,个人的观点是能用std::string的时候(不需要考虑兼容),就尽量不要用char *,费心费力还容易写错。

这个已经超出了a的长度,在vs中能输出,但提示变量a已经被破坏,正常a应该存放两个字符,末尾以\0结束。如果能正常输出,且不提示错误的话,和具体的编译器有关,比如vc的显示结果后会延迟1秒,dev-c++则没有。

strcpy()是C标准函数。
该函数不会检查数组越界的情况!!!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏