【问题标题】:Range check error in C++Builder (RAD Studio)C++Builder (RAD Studio) 中的范围检查错误
【发布时间】:2021-08-11 00:20:39
【问题描述】:

我在处理字符串数组时遇到了“范围检查错误”。据我了解,这意味着我正在使用数组中不存在的索引。

我的头文件中的类和函数:

AnsiString toBin(int n) {
    AnsiString zero = "0";
    int len;
    AnsiString result;
    while (n != 0) {
        result += (n % 2 == 0 ? "0" : "1");
        n /= 2;
    }
    len = result.Length();
    while (result.Length() < 8)
        result = zero + result;
    return result;
}
                    
int toInt(AnsiString bin) {
    int start = 1;
    int result = 0;
    for (int i = 0; i < 8; i++) {
        result += (int)bin[i] * start;
        start * 2;
    }
    return result;
}
                
class enc_dec {
private:
    AnsiString stext;
    AnsiString skey;
                
public:
    enc_dec(AnsiString t, AnsiString k) {
        stext = t;
        skey = k;
    }
                
    AnsiString XOR() {
        if (skey == "") {
            Application->MessageBox(L"Error!", L"No Key", MB_OK);
            return "";
        }
        AnsiString cry = "";
        int key = skey[1] + 0;
        AnsiString keyBin = toBin(key);
        AnsiString temp = "";

        // AnsiString output[stext.Length()];
        std::vector<AnsiString>output;
        for (int i = 1; i < stext.Length(); i++) {
            temp = toBin(stext[i]);
            for (int j = 1; j < 8; j++) {
                if (temp[j] == keyBin[j])
                    temp[j] = '0';
                else
                    temp[j] = '1';
            }
            output.push_back(temp[i]);
        }
        for (int i = 0; i < stext.Length(); i++)
            cry += char(toInt(output[i]));
        return cry;
    }
};

我的.cpp 文件:

void __fastcall TForm1::Button1Click(TObject *Sender){
    enc_dec temp(Edit1->Text,Edit2->Text);
    temp.XOR();
}

设计:

我在更新前发现了一个错误,“范围错误”尚未解决。

【问题讨论】:

    标签: c++ c c++builder rad-studio


    【解决方案1】:

    与标准 C++ 字符串和数组以 0 为索引不同,AnsiString 以 1 为索引。它的有效字符索引是 1 &lt;= N &lt;= Length,而不是 0 &lt;= N &lt; Length,因为您的 for 循环是为编写的。

    此外,在 XOR() 中,return; 不应编译,因为 XOR() 被声明为返回 AnsiString。您需要return 一个实际值(即return "";)或者throw 一个异常而不是使用Application-&gt;MessageBox()

    另外,AnsiString output[stext.Length()];not standard C++。您应该为您的阵列使用std::vectorSystem::DynamicArray

    【讨论】:

    • 我现在可以看到索引 0 导致范围错误。我按照您的建议进行了更改,但现在每次尝试运行时程序都会崩溃。
    • @yahya 那么您还有其他需要修复的错误。但我们看不到你在做什么。请使用minimal reproducible example 更新您的问题。
    • 我已经更新了这个问题,我希望这就是你所说的最小可重现示例的意思。我创建了一个新的 VLC,它只包含与问题相关的元素。
    • minimal reproducible example 将包含所用输入的示例以及输出应该的样子。这段代码的目标是什么?在任何情况下,当您将 for 循环更新为从索引 1 开始时,您并没有将它们更新为也使用 &lt;= 而不是 &lt;,因此您正在跳过字符串中的最后一个字符。此外,start * 2; 是空操作,因为结果不会保存在任何地方
    猜你喜欢
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2016-06-20
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    相关资源
    最近更新 更多