c++ - 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;
}
解决方案
问题很可能是这个循环(来自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++ 的一些基础知识。
推荐阅读
- php - 不允许对 UploadedFile 进行序列化(仅在达到最大大小时)
- mysql - 不使用主键时 MySQL 中的 UPSERT
- javascript - 如何正确全局注册和使用 Vue Rangedate Picker 组件?
- php - 如何使用一维数组的特定键构建分层数组
- sql - Postgres 数组值必须开始
- php - 基于值列的文本文件上的PHP计数行/行
- java - 带有法语口音的C在jsp中未正确显示
- dart - 如何创建用于导入本地字体文件的 dart 包
- http - http:// 是否被视为具有方案 http 和空路径的 URI?
- vuejs2 - 如何在单元测试中更新组件的属性?