返回具有新数组成员

时间:2021-03-31 19:44:10

标签: c++

我正在尝试执行类似于下面的代码片段的操作,但程序在 main 退出之前崩溃

HEAP Invalid address specified to RtlValidateHeap

这个想法是有一个函数来创建一个结构体,填充结构体的成员数组并返回结构体。

struct Sentence
{
    int char_count;
    char* characters;
    Sentence() {}
    Sentence(int input_char_count) : char_count(input_char_count) {
        characters = new char[char_count];
    }

    ~Sentence()
    {
        delete[] characters;
    }
};


Sentence write_alphabet(int length)
{
    Sentence s(length);

    for (int i = 0; i < length; i++)
        s.characters[i] = 'a' + i;

    return s;
}


int main()
{

    Sentence a_to_m;

    a_to_m = write_alphabet(length);
}

我用 characters 创建了 new,所以 delete[] 应该没问题吧?

0 个答案:

没有答案
相关问题