首页 > 解决方案 > Visual C++ 断言 - 字符串下标超出范围

问题描述

我的程序是Advent of Code 2015 中第 6 天问题的解决方案。当我使用“Start without Debugging”并在输出窗口中输入拼图输入时出现错误。该图像包含我收到的确切错误。该错误与“字符串下标超出范围”有关。我想帮助解决这个错误。

const int r = 1000;//global variable
const int c = 1000;//global variable
int lights[r][c];//global array

void instruction(string inp)//extracting OFF, ON, or toggle indication from the instruction
{
    int* loc;
    int coord[4] = { 0 };
    char cond = inp[7];
    loc = &coord[3];

    switch (cond)
    {
    case 'f':
        coordinates(loc, inp);
        execute(coord, cond);
        break;
    case 'n':
        coordinates(loc, inp);
        execute(coord, cond);
        break;
    default:
        coordinates(loc, inp);
        execute(coord, cond);
        break;
    }
}

void coordinates(int* loc, string inp)//extracting coordinates from the instruction
{
    int i, k = 0, l;
    l = inp.length()-1;
    for (i = l; inp[i] != ','; i--)
    {
        *loc += (inp[i]-'0') * pow(10,k);
        k++;
    }
    i--;
    loc--;
    k = 0;
    for (; inp[i] != ' '; i--)
    {
        *loc += (inp[i]-'0') * pow(10,k);
        k++;
    }
    i = i - 9;
    loc--;
    k = 0;
    for (; inp[i] != ','; i--)
    {
        *loc += (inp[i]-'0') * pow(10,k);
        k++;
    }
    i--;
    loc--;
    k = 0;
    for (; inp[i] != ' '; i--)
    {
        *loc += (inp[i]-'0') * pow(10,k);
        k++;
    }
}

void execute(int coord[], char cond)
{
    int i, j;
    for (i = coord[0]; i <= coord[2]; i++)
    {
        for (j = coord[1]; j <= coord[3]; j++)
        {
            if (cond == 'f')
                lights[i][j] &= 0;
            else if (cond == 'n')
                lights[i][j] |= 1;
            else
                lights[i][j] = ~lights[i][j];
        }
    }
}

int main()
{
    int i, j, k, count = 0;
    string inp;

    for (i = 0;;i++)
    {
        cout << "Enter an instruction" << endl;
        cin >> inp;

        if (inp != "xx")//To manually move to counting the number of lights turned ON
            instruction(inp);
        else
        {
            for (j = 0; j < r; j++)
            {
                for (k = 0; k < c; k++)
                {
                    if (lights[j][k])
                        count++;
                }
            }
            cout << endl << "Number of lights lit " << count;
            break;
        }
    }
    return 0;
}

标签: c++visual-studio-2019

解决方案


问题很可能是这个循环(来自coordinates函数):

l = inp.length()-1;
for (i = l; inp[i] != ','; i--)
{
    *loc += int(inp[i]) * (10 ^ k);
    k++;
}

在循环的第一次迭代中,然后i将等于l字符串的长度,这是超出范围的。

您也不会检查您是否在第二个方向上越界(i变为负数)。您在coordinates函数的所有循环中都有这个问题。


另一方面,将字符int转换为不会将数字字符转换为其相应的整数值。

假设 ASCII 编码(最常见的可用编码),那么字符'2'(例如)将具有整数值50

^运算符也是按位异,而不是任何类型的“幂”或“引发”运算符。看来您可能需要花更多时间了解 C++ 的一些基础知识。


推荐阅读