C ++ - Char数组以某种方式初始化为错误的大小

问题描述 投票:0回答:1

我正在从头开始编写一个字符串类作为类赋值的一部分,我在编写子字符串函数时遇到了麻烦。据我所知,它与初始化为错误大小的字符数组有关。

据我所知,字符串类中的其他所有内容都非常有效。我在Ubuntu的Qt创建者中写这个。

string string::substring(unsigned int startIndex, unsigned int endIndex) const {
    if (startIndex >= endIndex) {
        string s;
        return s;
    }
    if (endIndex > length) endIndex = length;

    int rlength = endIndex - startIndex;

    char* r = new char[rlength];

    for (int i = 0; i < rlength; i++) {
    r[i] = chars[i + startIndex];

    }

    string s2(r);
    return s2;
}

我期待看到的:

"This is a test".substring(0, 4) -> "This"
"This is a test".substring(6, 8) -> "is"
"This is a test".substring(9, 10) -> "a"

我实际看到的内容:

"This is a test".substring(0, 4) -> "This"
"This is a test".substring(6, 8) -> "is"
"This is a test".substring(9, 10) -> "a�;�"

根据我自己的故障排除,看起来r以某种方式被初始化为比预期更大的尺寸,在预期文本之后留下一些垃圾。有谁知道为什么会发生?

c++ arrays qt gcc
1个回答
2
投票

虽然你没有提供string(char*)构造函数的代码,但它可能告诉字符串长度的唯一方法是扫描null终止符。但是,代码中的字符数组r缺少空终止。

将一个char添加到数组的长度,并将其设置为'\0'以解决此问题:

char* r = new char[rlength+1];
for (int i = 0 ; i < rlength ; i++) {
    r[i] = chars[i + startIndex];
}
r[rlength] = '\0';
© www.soinside.com 2019 - 2024. All rights reserved.