# Why can't I return a vector<vector<int>> (Process returned -1073741819 (0xC0000005))

1

I tried to make a grid-based program in C++. But each time I run it, I get the same error (Show in title). I know it is quite a common error but after reading carefully through the code, I wasn't able to spot any mistake:

``````#include <iostream>
#include <vector>

using namespace std;

using grid = vector<vector<int>>;

int getNeighboursCount(grid g,int x,int y)
{
int nCount = 0;
if(x > 0 && y > 0){if(g[x-1][y-1] == 1){++nCount;};};
if(x > 0){if(g[x-1][y] == 1){++nCount;};};
if(y > 0){if(g[x][y-1] == 1){++nCount;};};
if(x < g.size() && y < g[x].size()){if(g[x+1][y+1] == 1){++nCount;};};
if(x < g.size()){if(g[x+1][y] == 1){++nCount;};};
if(y > g[x].size()){if(g[x][y+1] == 1){++nCount;};};
if(x > 0 && y < g[x].size()){if(g[x-1][y+1 == 1]){++nCount;};};
if(x < g.size() && y > 0){if(g[x+1][y-1] == 1){++nCount;};};
return nCount;
}

grid testCell(grid g, grid gN, int x, int y)
{
gN = g;
auto nCount = getNeighboursCount(g, x, y);
if(g[x][y] == 1) //1 == TRUE == alive
{
if(nCount == 3 || nCount == 2){gN[x][y] == 1;} //Keep status
else
{
gN[x][y] = 0;
}
}
else if(g[x][y] == 0)
{
if(nCount == 3){gN[x][y] = 1;}
else {gN[x][y] == 0;};
}
return gN;
}

grid step(grid g, grid gN)
{
for(int i = 0; i < g.size(); ++i)
{
for(int j = 0; j < g[i].size(); ++j)
{
gN = testCell(g, gN, i, j);
}
}
// works fine till here...
return gN;
}

int main()
{
grid g =
{ ...
// 40 times 40 grid of 0
};
output(g);
string useless;
grid gN = g;
while(getline(cin, useless))
{
gN = step(g, gN);
output(gN);
}

}
``````

So, when I Start the program it prints out the whole grid as it is supposed to do. But when it gets to the point where `gN = step(...);` I get an error. But I was able to spot that it has something to do with the `return gN;` statement of the swap() function.

thx for helping

c++
vector
return
c++17

0

You're trying to test out-of-bounds conditions inside `getNeighboursCount()`, but you are not doing it completely right. In lines

``````    if(x < g.size() && y < g[x].size()){if(g[x+1][y+1] == 1){++nCount;};};
if(x < g.size()){if(g[x+1][y] == 1){++nCount;};};
if(y > g[x].size()){if(g[x][y+1] == 1){++nCount;};};
if(x > 0 && y < g[x].size()){if(g[x-1][y+1 == 1]){++nCount;};};
if(x < g.size() && y > 0){if(g[x+1][y-1] == 1){++nCount;};};
``````

each test for overflow (e.g. `x < g.size()`) is incorrect. The `getNeighbourghsCount()` method never gets called with an `x` that would not satisfy the condition, `x` is always smaller than the size of the container, because it's 0 based indexed. One way to fix it would be to change the condition to `x < g.size() - 1`

There are other problems, e.g. `g[x-1][y+1 == 1]` is certainly a typo. But this might get you started...

User contributions licensed under CC BY-SA 3.0