program moving objects

the program actually says that there is an error or at times it just doesnt run

void moveplane(int **arr, int row,int col)
{
string direction;
for (int i=0; i<row; i++)
{
for (int j=0; j<col; j++)
{
if (arr[i][j]==1)
{
cout<<"would you like to move up (u)/down (d)/right (r)/left (l)"<<endl;
cin>>direction;
if ((direction=="r") && (j<col))
{
arr[i][j+1]=arr[i][j];
}
else if ((direction=="l") && (j>0))
{
arr[i][j-1]=arr[i][j];
}
else if ((direction=="u") && (i>0))
{
arr[i+1][j]=arr[i][j];
}
else if (direction=="d" && (i<row))
{
arr[i-1][j]=arr[i][j];
}
else
{
cout<<"would you like to move up (u)/down (d)/right (r)/left (l)"<<endl;
cin>>direction;
}

}
}
}
}


You seem to be going out of the bounds of your array.

In this piece of code...

1
2
3
4
5
				if((direction == "r") && (j < col))
				{
					arr[i][j + 1] = arr[i][j];
				}


... if j is one less than col (the last entry in the array) then your statement arr[i][j + 1] will be accessing the element beyone the last element of the array.

Remember an array bounds are from 0 to N-1. So accessing element N itself is out of bounds.
ok so how would i actually correct it?
Well of (col - 1) is the LAST element, and you want to move right, then you can only legally move right if you are at most (col - 1 - 1) elements away from the end.
Last edited on
Topic archived. No new replies allowed.