#include <iostream>int main(){ using namespace std; char a[3]; strcpy(a,"affd sfasdfsdf"); cout << a[5] << endl; cout << a << endl;
}这里的输出结果居然是:saffd sfasdfsdf奇怪,a的长度明明是3,为什么会有这样的输出结果呢?
1 回答
忽然笑
TA贡献1806条经验 获得超5个赞
关于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 *
,费心费力还容易写错。
- 1 回答
- 0 关注
- 640 浏览
添加回答
举报
0/150
提交
取消