Reputation: 29
I was searching for a solution, but I couldn't use any without an error. Im trying to draw a map in console, using multidismentional array. I want to have more maps, but I can`t do it without spamming useless code. This is the map:
char map2[11][15] = {
"###^######^###",
"#L #",
"^S #",
"#S #",
"# K #",
"########### #",
"#G #",
"# #### #",
"# #M #",
"# @ # #",
"## ########^##"};
and this is moving script:
void Game::showing_different_maps()
{
differentmap= true;
while (differentmap)
{
system("cls");
for(int i = 0; i < 81; i++) // i < map2[y][]
{
cout << somemap[i] << endl; // drawing a map !THIS CAUSES CRASH!
}
system("pause>nul"); // this line prevent lagging somehow
if(GetAsyncKeyState(VK_UP)) // arrows to move on axis (y, x)
{
mapka.move(-1, 0);
}
if(GetAsyncKeyState(VK_DOWN))
{
mapka.move(1, 0);
}
if(GetAsyncKeyState(VK_RIGHT))
{
mapka.move(0, 1);
}
if(GetAsyncKeyState(VK_LEFT))
{
mapka.move(0, -1);
}
}
}
and here is what I could find in the internet.
Wut wut(3, 13);
Maps *wsk;
pointer = &wut;
char (*somemap)[81] = new char[81][81];
somemap= &map2[81];
pointer = &wut;
pointer -> get_in_area();
thing I want to do is to: in some part of the code, I want the pointer to be map2. I managed to make pointer "pointer" to show void get_in_area() in class Maps, but Console crashes, when I want to draw the map with somemap pointer in second code sample. It works, when instead of somemap[i] I put map2[i]. I`m sorry if I missed anything, I'm beginner and English is not my first language. I made this script with this tutorial: https://www.youtube.com/watch?v=7gpH7bOS350
Upvotes: 1
Views: 89
Reputation: 148880
You should learn how to pass parameters instead of using global (map2
) or static (81) variables. If you declare:
void Game::showing_different_maps(int n, int m, char map[n][m])
{
String differentmap= true;
while (differentmap)
{
system("cls");
for(int i = 0; i < n; i++) // i < map2[y][]
{
cout << somemap[i] << endl; // drawing a map !THIS CAUSES CRASH!
}
you should no longer crash...
But anyway, for this usage, I would use a pointer to pointer instead of a 2d array:
char *map2[]= {
"###^######^###",
"#L #",
"^S #",
"#S #",
"# K #",
"########### #",
"#G #",
"# #### #",
"# #M #",
"# @ # #",
"## ########^##"};
And then
void Game::showing_different_maps(int n, char **map)
Upvotes: 0
Reputation:
This is how you would create a 2-dimensional array:
typedef int T;
void f()
{
T ** map = new T*[10];
for (int i = 0; i < 10; i++)
{
map[i] = new T[10];
}
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
map[i][j] = i*j;
}
}
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
std::cout << map[i][j] << "\t";
}
std::cout << std::endl;
}
}
This will output a generic multiplication table.
If you want more dimensions you would simply add one more step in creation:
T*** map = new T**[10];
for (int i = 0; i < 10; i++)
{
map[i] = new T*[10];
}
...
Upvotes: 1