Hi, I tried to create console game
in my first attempt, i maked a 2d array in main and controlled a character with GetAsyncKeyState,
then I asked some people how I can make matrixes in classes
and make different matrixes for any part of the game ( with OOP ), I tried what I did on normal 2d arrays ( not created with pointers ) and I stuck in that how
I can move the character of the map ( matrix )
(it don't give me compile error but it crashes when I press the move keys,
I declared which line will crash by command )
Error :
Unhandled exception at 0x010B2D17 in main.cpp.exe: 0xC0000005: Access violation
writing location 0x010BDC25.
#include<iostream>
#include"Windows.h"
usingnamespace std;
class Level
{
int sx, sy; //Size
public:
int x, y;
char** MapData;
// 2D variable pointer array to
// hold the map
Level()
{
y = 1;
x = 1;
MapData = newchar*[1000];
for (int i = 0; i<1000; i++)
MapData[i] = newchar[1000];
}
char**& Map(int ht, int wd)
// Resizes the map to our needs,
// and allows us to assign it data
// as a normal array in main.
{
MapData = newchar*[ht];
for (int i = 0; i<ht; i++)
MapData[i] = newchar[wd + 1];
sx = ht; sy = wd;
return MapData;
}
void Move(int V, int H)
{
int y2 = y + V;
int x2 = x + H;
if (MapData[y2][x] == ' ')
{
MapData[y][x] = ' '; // Crash is in this line
y += V;
MapData[y][x] = '@';
}
if (MapData[y][x2] == ' ')
{
MapData[y][x] = ' ';
x += H;
MapData[y][x] = '@';
}
}
};
int main()
{
bool gameOver = false;
Level l1;
// l1.x = 1;
// l1.y = 1;
char* mymap[] = {
"####",
"#@ #",
"# #",
"####" };
// mymap is a temp object to hold data.
l1.Map(4, 4) = mymap;
// Initializes Map with Size and Data.
while (!gameOver)
{
system("cls");
for (int i = 0; i < 4; i++)
cout << l1.MapData[i] << endl;
system("pause>nul");
if (GetAsyncKeyState(VK_UP))
l1.Move(-1, 0);
if (GetAsyncKeyState(VK_DOWN))
l1.Move(1, 0);
if (GetAsyncKeyState(VK_LEFT))
l1.Move(0, -1);
if (GetAsyncKeyState(VK_RIGHT))
l1.Move(0, 1);
}
}
you need to print them before the crash line. I saw the initial but I also see this
y += V;
and this
Move(int V,
and this
l1.Move(-1,
which could lead to a -1 index if the loop executes the +=V too many times before y is incremented somewhere else with a positive value. I am pretty darn sure it would crash if you keep hitting the up key.
print x&y and show that the indexes are legal when it crashes. Remember, it may do several iterations before it crashes, and it may not print the latest print statement before it crashes due to buffered IO. You can add a flush after all the prints to force that, if you like; this helps me to debug.....