#include <iostream>
using namespace std;
void initializeMap(int mapSizeX, int mapSizeY, int map[][10])
{
// Map details:
// 0 = # (wall)
// 1 = space (free space)
// 2 = x (player)
for(int x = 0; x < mapSizeX; x++)
{
map[x][0] = 0;
}
for(int y = 0; y < (mapSizeY - 2); y++)
{
map[0][y] = 0;
for(int x = 0; x < (mapSizeX - 2); x++)
{
map[x][y] = 1;
}
map[mapSizeX][y] = 0;
}
for(int x = 0; x < mapSizeX; x++)
{
map[x][mapSizeY - 1] = 0;
}
}
void paintMap(int mapSizeX, int mapSizeY, int map[][10])
{
for(int y = 0; y < mapSizeY; y++)
{
for(int x = 0; x < mapSizeX; x++)
{
switch(map[x][y])
{
case 0:
cout << "#";
break;
case 1:
cout << " ";
break;
case 2:
cout << "x";
break;
}
cout << map[x][y];
}
cout << endl;
}
}
int main()
{
int mapSizeX = 10;
int mapSizeY = 10;
int map[10][10];
initializeMap(mapSizeX, mapSizeY, map);
paintMap(mapSizeX, mapSizeY, map);
cout << endl << endl;
return 0;
}
My code compiles perfectly fine without errors but when I try to run it, it just says “Segmentation fault”. I’ve done some research and I don’t understand why I get it because I don’t use pointers at all. How do I fix this? I compile it using g++ and run it by just typing ./main in the terminal.
This is illegal. Valid values of the index run from
0tomapSizeX - 1.The line should be:
One assumes that this is the desired output?
If so, you have a number of other off-by-one errors in your
initializeMapfunction. Instead of:and
you should use
and
respectively.
BTW, here’s a cleaner way to write
initializeMap:And you can call it with just
No need to pass the size, the compiler will figure it out automatically.