I'm quite new to programming and for my Object Oriented class (in C++), we have a 2d array with random groupings of "X". I have to use a recursive function to find the different groupings and clear them. As of right now, I check if the spot is an X, clear it, then check the 8 positions around it (including diagonals), and if one of the positions in an X, I call the function again but on that location. My idea is that if I find one X, I will be able to get all the X's around it in one go, thus, I can count it as a group when I find an X.
At the end of the function, I basically loop through all the spots and call the recursive function again if there is another X. However, I keep getting segmentation faults and I'm not sure why. Any help would be greatly appreciated!
void Recurssive(string Array[][72],int Pos1, int Pos2)
{
int One=1;
int Two=1;
//cout<<"Test 2";
if(Array[Pos1][Pos2]=="X")
{
Array[Pos1][Pos2]="0";
if(Array[Pos1+1][Pos2]=="X")
{
Recurssive(Array,Pos1+1,Pos2);
}
if(Array[Pos1-1][Pos2]=="X")
{
Recurssive(Array,Pos1-1,Pos2);
}
if(Array[Pos1][Pos2+1]=="X")
{
Recurssive(Array,Pos1,Pos2+1);
}
if(Array[Pos1][Pos2-1]=="X")
{
Recurssive(Array,Pos1,Pos2-1);
}
if(Array[Pos1+1][Pos2+1]=="X")
{
Recurssive(Array,Pos1+1,Pos2+1);
}
if(Array[Pos1-1][Pos2-1]=="X")
{
Recurssive(Array,Pos1-1,Pos2-1);
}
if(Array[Pos1+1][Pos2-1]=="X")
{
Recurssive(Array,Pos1+1,Pos2-1);
}
if(Array[Pos1-1][Pos2+1]=="X")
{
Recurssive(Array,Pos1-1,Pos2+1);
}
}
for(int i=1;i<22;i++)
{
for(int j=1;j<72;j++)
{
if(Array[i][j]=="X")
{
Recurssive(Array,i,j);
}
}
}
}
Here is the output of the array I am looping through
X
X
X XXXXXXXXXXXXXXX
X XXXXXXXXXXXXXXX
X XXXXXXXXXXXXXXX XXXX
XXXX XXXXXXXXXXXXXXX XXX XXX
X XXX XXX
XXXXXXXXXXXXXX X XXX XXX
XX XX X XXX XXX
XX XX X XXX XXX
XX XX X XXXX
XX XXXXX XX X
XX XX X
XX XX X
XXXXXXXXXXXXXX X
X
X
X
X
X
forallows forjto be up to 71, while in theRecurssivefunction it can be called with j+1 (thus going out of the range for the array). It is the same forij = 71, you are accessing72nd index inf(Array[Pos1][Pos2+1]=="X"), which is access out of bounds, due to arrays being 0-based. Don't know, if the same can be said for theiindex, due to lacking minimal reproducible example (hence - not knowing both of the dimensions of the array), but suspect that it has the same issue.i" Technically - one cannot be certain that it's the same fori, due to the fact, that this dimension of the array is not shown in the question. One can only guess, that it might be an issue.