簡體   English   中英

C ++字符串附加函數怪異行為

[英]C++ String Append Function Weird Behavior

我有一個正在處理的字符串類的append函數部分,使用時會發生一些非常奇怪的事情。 當我打印出來的函數內部的附加字符串,然后又main ,它的工作原理。 但是當我注釋掉函數內部的打印部分並將打印留在main ,輸出是一些隨機字符。 這是代碼:

String.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中的打印功能時:

是什么原因造成的? 謝謝。


編輯:

分配運算符:

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處理動態分配(這需要一些努力,請考慮一下構造函數,析構函數,賦值,復制構造函數/賦值),或者需要將數據復制到以前分配的數據中緩沖。

有關復制字符數組的方法,請參見此問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM