gpt4 book ai didi

C++ 字符串追加函数奇怪的行为

转载 作者:行者123 更新时间:2023-11-28 02:10:57 25 4
gpt4 key购买 nike

我有一个我正在处理的字符串类的追加函数部分,在使用时发生了一些非常奇怪的事情。当我在 inside 函数中打印出附加字符串,然后也在 main 中打印时,它起作用了。但是当我注释掉函数内的打印部分并将打印留在 main 中时,输出是一些随机字符。这是代码:

字符串.cpp:

void String::append(const String buf)
{
char c[99];

for (auto i = 0; i < this->length(); ++i) {
c[i] = this->cstr()[i];
}

for (auto i = this->length(); i < (this->length() + buf.length() + 1); ++i) {
c[i] = buf.cstr()[i - this->length()];
}

*this = c;
printf("%s\n", *this); // if I comment this line out then the append function doesn't work properly
}

主要内容:

int main()
{
String a = "Hello";
String b = "Hi";
a.append(b);
printf("%s\n", a);
}

当使用两个打印函数时,输出是这样的:

当只使用main中的print函数时:

这可能是什么原因造成的?谢谢。


编辑:

赋值运算符:

String &String::operator=(char* buf) {
_buffer = buf;
return *this;
}

构造函数:

String::String(char* buf) : _buffer(buf), _length(0) {
setLength();
}

最佳答案

char c[99];

是一个自动存储时长的数组。在离开 append() 函数后使用指向第一个元素(又名 c)的指针是未定义的行为。

通过赋值运算符存储它不会保存数据或阻止它被删除。

为了保留数据,您要么需要使用 new 和 delete 处理动态分配(这需要一些努力,考虑构造函数、析构函数、赋值、复制构造函数/赋值),要么需要将数据复制到您之前分配的缓冲区。

有关复制字符数组的方法,请参阅 this question

关于C++ 字符串追加函数奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35690297/

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