Answer the question
In order to leave comments, you need to log in
Why is the array going out of bounds?
Hello. I'm a beginner in C++, so I'm having trouble with its strong typing. I'm trying to use queues. I pass values from the queue to the array, but for some reason an uncaught exception appears, which I usually have when I go beyond the array. I will give a shortened code with a method (the problem area is marked there):
class KittyClass {
public:
int coord[9][2];
int x, a, b, w, num;
std::queue<int> queue;
KittyClass() {
x = 0;
num = 1;
}
bool goKittiesBFS(std::string arr[6][6]) {
int y = 1, num = 1, g = 0;
string cats[2];
string myArrStr;
string myCompStr;
string s;
for (int i = 0; i < 9; i++)
{
for (int g = 0; g < 6; g++)
{
for (int b = 0; b < 6; b++)
{
//strcpy_s(arrStr, arr[w][b].c_str());
myArrStr = arr[g][b].c_str();
myCompStr = "k" + std::to_string(num);
//strcpy_s(compStrPart, s.c_str());
//strcat_s(compStr,compStrPart);
std::cout << myArrStr << " : " << myCompStr << std::endl;
if (myArrStr == myCompStr)
{
queue.push(g);
queue.push(b);
}
}
}
(b >= 6) ? b = 0 : b;
(g >= 6) ? g = 0 : g;
num++;
}
// ----------------
// Тут происходит выход за пределы:
for (int i = 0; i < 9; i++)
{
// cats[9][2] // queue имеет 18 чисел
cats[i][0] = queue.front();
queue.pop();
cats[i][1] = queue.front();
queue.pop();
}
return true;
}
}
Answer the question
In order to leave comments, you need to log in
You have within the same class 3 times the variable g is created, 2 times b. For such a naming style, Artemy Lebedev would say "Get out of the profession"
// cats[9][2] // queue has 18 numbers
//массив 2 строки
string cats[2];
...
for (int i = 0; i < 9; i++)
{
//Перепутан порядок индексов. Первый индекс это номер строки в массиве, второй номер символа в строке.
//И вы должны быть точно уверены что в строках будет не менее 9 символов.
cats[i][0] = queue.front(); // <--- должно быть cat[0][i]
queue.pop();
cats[i][1] = queue.front(); // <--- должно быть cat[1][i]
queue.pop();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question