数组的循环引发读取访问异常



我正在使用干净的C++编写一个简单的战舰控制台游戏。我正在试着写一个方法,用会返回一些甲板的船。它看起来像这样:

int Field::get_deck_number(int x, int y)
{
int temp_x = x,
temp_y = y,
deck_counter = 0;
if (arr[y][x] == field_sign || arr[y][x] == border_sign)
{
return 0;
}
for (int direction = 0; direction < 4; direction++)
{
temp_x = x;
temp_y = y;
while (arr[temp_y][temp_x] != field_sign || arr[temp_y][temp_x] != border_sign || arr[temp_y][temp_x] != tried_sign)
{
if (arr[temp_y][temp_x] == ship_sign || arr[temp_y][temp_x] == destroyed_sign)deck_counter++;
if (direction == 0)
{
temp_y++;
continue;
}
if (direction == 1)
{
temp_y--;
continue;
}
if (direction == 2)
{
temp_x++;
continue;
}
if (direction == 3)
{
temp_x--;
continue;
}
}
}
return deck_counter;
}

while循环条件存在问题。这是一个无限循环,所以我将在几次迭代后获得读取访问冲突。

问题在于逻辑OR和and(||,&&(的使用不当。此外,我在代码中发现了其他逻辑问题。现在它工作正常。

int Field::get_deck_number(const int &x, const int &y)
{
int temp_x = x,
temp_y = y,
count = 0,
deck_counter = 0;
if (arr[y][x] == field_sign || arr[y][x] == border_sign || arr[y][x] == tried_sign)
{
return 0;
}
for (int direction = 0; direction < 4; direction++)
{
temp_x = x;
temp_y = y;
count++;
while (arr[temp_y][temp_x] != field_sign && arr[temp_y][temp_x] != border_sign && arr[temp_y][temp_x] != tried_sign)
{   
if (arr[temp_y][temp_x] == ship_sign || arr[temp_y][temp_x] == destroyed_sign)deck_counter++;
if (direction == 0)
{
temp_y++;
continue;
}
if (direction == 1)
{
temp_y--;
continue;
}
if (direction == 2)
{
temp_x++;
continue;
}
if (direction == 3)
{
temp_x--;
continue;
}
}
}
return deck_counter - count + 1;
}

最新更新