不显示字符串源

strcpy source is not displayed

本文关键字:字符串 显示      更新时间:2023-10-16
 #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",然后再加上b,b显示为空白,为什么?

因为有了空间,a[]缓冲区不足以容纳b的副本,并且您试图使它这样做会损坏堆栈,从而产生未定义的行为。任何事情都可能发生,但在您的情况下,很可能是用终止的NUL覆盖下一个变量(即b)的第一个字节,使b显示为空。

拼出来:

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

必须提示:尽可能使用std::string