gpt4 book ai didi

c++ - 不显示 strcpy 源

转载 作者:搜寻专家 更新时间:2023-10-31 00:12:19 26 4
gpt4 key购买 nike

 #include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main ()
{
char a[]="one string",b[]="twostrings";
strcpy (a,b);

cout<<"A="<<a;
cout<<endl<<"B="<<b<<endl;
}

a 和 b 显示后是相等的,但是如果我像这样输入一个空格 b[]="two strings",然后 cout b ,它显示 b 为空白,为什么?

最佳答案

因为有空间,a[] 缓冲区不够大,无法容纳 b 的拷贝,而您尝试这样做会破坏堆栈产生未定义的行为。任何事情都可能发生,但在您的情况下,它很可能会用终止符 NUL 覆盖下一个变量(即 b)的第一个字节,这样 b 显示为空。

拼写出来:

a          b
one string0two strings0 // original content 0=NUL
two strings0wo strings0 // after copy

强制提示:尽可能使用 std::string

关于c++ - 不显示 strcpy 源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30524882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com