strcat目标数组的大小

wjm*_*wjm 6 c c++ strcat

参加以下计划:

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char a[8] = "Hello, ";
    char b[7] = "world!";

    strcat(a, b);

    cout << a;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,a并且b其大小与指定的字符串相同.

文件规定,对于strcat(a, b)工作,a需要足够大,以包含串联的结果字符串.

不过,cout << a显示"Hello, world!".我进入未定义的行为吗?

Ark*_*ady 11

"我进入未定义的行为吗?"

是.已经写了[]末尾的区域.这次它起作用了,但可能属于别的东西.

在这里,我使用结构来控制内存布局,并演示它:

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    struct S {
        char a[8];
        char b[5];
        char c[7];
    };

    S s;
    strcpy( s.a , "Hello, " );
    strcpy( s.b , "Foo!" );
    strcpy( s.c , "world!" );


    strcat(s.a, s.c);

    cout << s.a << endl;
    cout << s.b << endl;

    cin.get();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这输出:

Hello, world!
orld!
Run Code Online (Sandbox Code Playgroud)

代替:

Hello, world!
Foo!
Run Code Online (Sandbox Code Playgroud)

strcat()遍布b [].

请注意,在现实生活中的例子中,这样的错误可能会更加微妙,并让您想知道为什么完美无辜的函数会在250行之后发生崩溃并且可怕地烧毁.;-)

编辑:我还建议你使用strcat_s吗?或者,更好的是,std :: strings:

#include <string>
#include <iostream>

using namespace std;

int main()
{
    string a = "Hello, ";
    string b = "world!";
    a = a + b;
    cout << a;
}
Run Code Online (Sandbox Code Playgroud)

  • +1.一个不那么好的问题很好的答案. (2认同)