I currently have an assignment to make a board game in C++. I'm currently facing a problem with vectors because it keeps giving me 'Segmentation fault'. I have put an arrow comment at the part of my code which I think is the problem, It is in the Map::DisplayMap() function. But, I do not know what to do to fix it.
#include <iostream>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <ctime>
#include <string>
using namespace std;
struct Map
{
vector<vector<char>> board;
int DimX, DimY;
void CellContent(int DimX, int DimY);
void DisplayMap();
int getDimensions();
};
void Map::CellContent(int DimX, int DimY)
{
char objects[] = {' ', ' ', ' ', ' ', ' ', ' ', 'X', '#', '@', '$'};
int noOfObjects = 10;
board.resize(DimY); // Create empty vector
for (int i = 0; i < DimY; ++i)
{
board[i].resize(DimX);
}
for (int i = 0; i < DimY; ++i) // put random Characters inside vector
{
for (int j = 0; j < DimX; ++j)
{
int ObjectNumber = rand() % noOfObjects;
board[i][j] = objects[ObjectNumber];
}
}
}
void Map::DisplayMap()
{
cout << " --__--__--__--__--__--__--__--" << endl; // Header
cout << " = Alien, defeat the Zombies! =" << endl;
cout << " __--__--__--__--__--__--__--__" << endl;
// Each Row
for (int i = 0; i < DimY; ++i)
{
// DisplayMap upper border
cout << " ";
for (int j = 0; j < DimX; ++j)
{
cout << "+-";
}
cout << "+" << endl;
// DisplayMap row number
cout << setw(2) << (DimY - i);
// DisplayMap cell content
for (int j = 0; j < DimX; ++j)
{
cout << "|" << board[i][j];// <========= The problem starts here, I think.
// << " "; // letak content
}
cout << "|" << endl;
}
// DisplayMap lower border
cout << " ";
for (int j = 0; j < DimX; ++j)
{
cout << "+-";
}
cout << "+" << endl;
// DisplayMap column number
cout << " ";
for (int i = 1; i <= DimX; ++i)
{
int digit;
digit = i / 10;
if (DimX >= 10)
{
cout << " ";
if (digit == 0)
{
cout << " ";
}
else
{
cout << digit;
}
}
}
if (DimX >= 10)
{
cout << endl
<< " ";
for (int j = 1; j <= DimX; ++j)
{
cout << " " << (j % 10);
}
}
else
{
for (int j = 1; j <= DimX; ++j)
{
cout << " " << (j % 10);
}
}
}
int main()
{
Map Map;
Map.DimX = 11;
Map.DimY = 5;
Map.DisplayMap();
}
From what I learned, Segmentation faults happen when I try to access something I'm not supposed to. I don't know what it really means and how that happens in my code.