gpt4 book ai didi

c++ 字符串行为在定义和在 strcat 函数中是不同的

转载 作者:行者123 更新时间:2023-11-30 03:37:40 25 4
gpt4 key购买 nike

#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
int len ;
strcat( str1, str2);
len = strlen(str1);
cout << len << endl<<str1<<endl;
return 0;
}

当我像这样初始化 str1 时 char str1[5]="hello"; ,C++ 编译器给我一个错误(意味着字符串的大小必须比给定的字符串大 1)。但在 strcat 中,我们将 str1str2 连接在一起,第一个字符串的大小为 10,字符串的长度也为 10(表示没有额外的空字符)。为什么这种行为会发生变化?我们在strcat 函数中是否将C++ 字符串转换为C 字符串,请解释。

最佳答案

Are we converting c++ string

不,您的程序中没有涉及 C++ 字符串(即 std::string)。

why is this changed behavior ?

你写了一个不同的程序,行为是不同的。

在第一种情况下,您的程序格式错误。该标准要求编译器在编译时通知您这一点。编译器也很容易检测到你的错误。变量的类型是“5 个字符的数组”。 6 个字符不适合 - 类型错误。类型在编译时已知。


在示例代码中,您使用了 strcat。如果你看一下this reference你会发现

The behavior is undefined if the destination array is not large enough for the contents of both src and dest and the terminating null character.

标准不要求编译器警告您未定义的行为。事实上,编译器通常很难证明程序具有未定义的行为 - 即使在这种特殊情况下它看起来很明显。

strcat 的参数是指针。您将正确类型的指针传递给 strcat。没有类型错误。该错误存在于错误的值中。这些值在运行时被复制到数组中(除非优化器做了一些魔术)。为了找出你的错误,编译器必须模拟程序的执行。对所有代码路径执行此操作将非常缓慢。因此,编译器将满足 strcat 前提条件的责任留给了程序员。

关于c++ 字符串行为在定义和在 strcat 函数中是不同的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40085108/

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