Segmentation Fault When Trying to Interact with a 2D Array C++ - c++

I'm attempting to interact with a 2D array thorough the Board class. However, I'm getting a segmentation fault when running the main file containing this code:
#include "Board.h"
int main(int argc, char** argv)
{
int height = 0;
int width = 0;
int pop_density = 0.8;
Board* c = new Board(height,width);
c->print();
c->populate(pop_density);
c->print();
//for (i )
cout << c->read_char_at_index(1,2) << endl;
delete c;
return 0;
}
This is the Board.cpp Code:
#include "Board.h"
//in board: make a fucntion that pulls from file
Board::Board(int h, int w)
{
m_height = h;
m_width = w;
m_array = new char* [m_height];
for (int i = 0; i < m_height; ++i)
{
m_array[i] = new char[m_width];
for (int j = 0; j < m_width; ++j)
{
m_array[i][j] = '-';
}
}
cout << "Made board" << endl;
}
Board::~Board()
{
for (int i = 0; i < this->m_height; ++i)
{
delete[] this->m_array[i];
}
delete[] this->m_array;
cout << "Destructed Board" << endl;
}
void Board::print()
{
for (int i = 0; i < this->m_height; ++i)
{
for (int j = 0; j < this->m_width; ++j)
{
cout << this->m_array[i][j] << " ";
}
cout << endl;
}
}
void Board:: populate(double density)
{
//seeding rand with time
srand(time(NULL));
int totalCells = this->m_height * this->m_width;
int cellsToFill = round(totalCells * density);
int cellsFilled = 0;
for (int i = 0; i < cellsToFill; ++i)
{
int randomRow = rand() % this->m_height;
int randomColumn = rand() % this->m_width;
this->m_array[randomRow][randomColumn] = 'X';
}
}
void Board:: write_char_at_index(int height, int width, char z)
{
cout << "pre" << endl;
cout << height << " " << width << endl;
m_array[height][width] = z;
cout << "Wrote" << endl;
}
char Board:: read_char_at_index(int height, int width)
{
return m_array[height][width];
cout << "read" << endl;
}
And the Board.h Code:
#ifndef BOARD_H
#define BOARD_H
#include <iostream>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
//This class is used to make a Board object
class Board
{
public:
Board(int h, int w);
~Board();
void print(); // Prints the board to cout
void populate(double density); // Populates board based on density input
void write_char_at_index(int height, int width, char z);
char read_char_at_index(int height, int width);
private:
char** m_array; // 2D array dynamically allocated during runtime
int m_height;
int m_width;
};
#endif
Any help or advice would be great, as I've already asked two classmates and they're not sure what the problem is. I know for sure the index I'm trying to assign the char value to is not out of bounds.

The input parameters of read_char_at_index are (1,2) in the main function. However, The Board object c is with height = 0 and width = 0. You can modify the value of height and width to large enough values, such as 10, 10.
int height = 10;
int width = 10;
int pop_density = 0.8;
Board* c = new Board(height, width);
c->print();
c->populate(pop_density);
c->print();
cout << c->read_char_at_index(1, 2) << endl;
The program may run without Segmentation Fault.
Note: The functions "write_char_at_index" and "read_char_at_index" may check the input values (height and width) to ensure the access to m_array member is safe.
if (height >= this->m_height || width >= this->m_width)
{
return;
}

Related

error: prototype for ' ' does not match any in class ' ';

I recently started coding in c++ and was doing a project. Currently I'm using multiple files, one as a header, one for cpp code, and one as a main file. I've been stuck on a problem for a while now and I just cant figure out whats wrong. Whenever I compile the cpp file I get the error prototype for ‘GradeCalculator::GradeCalculator(const int*, const int&)’ does not match any in class ‘GradeCalculator’. I would really love to get some help and explanation on whats going wrong, here's my code:
//main file:
#include <iostream>
#include "GradeCalculator.h"
#define NUM_ASSIGNMENTS 100
int main() {
int points[NUM_ASSIGNMENTS];
int newsize = 0;
GradeCalculator gradecalculator(points, newsize);
std::cout << "Grade Calculator\n" << std::endl;
std::cout << "================\n" << std::endl;
std::cout << "This program will calculate your grade average on your assignments.\n" << std::endl;
std::cout << "Your lowest grade will be dropped.\n" << std::endl;
newsize = gradecalculator.addPoints(points);
gradecalculator.printResults(points, newsize);
return 0;
}
//header file:
#ifndef DEMO_GRADECALC_H
#define DEMO_GRADECALC_H
#include <iostream>
class GradeCalculator{
private:
int points[100];
int size;
public:
GradeCalculator(int* points, int size);
int addPoints(int*points);
int dropLowest(int* points, int size);
explicit GradeCalculator(const int* points, const int size);
void printResults(int* points, int size);
virtual ~GradeCalculator();
};
#endif
//cpp file:
#include <iostream>
#include "GradeCalculator.h"
GradeCalculator::GradeCalculator(const int* points, const int &size){
}
int GradeCalculator::addPoints(int* points){
int sizeofarray = 0;
for( int j = 0; points[j] = '\0'; j++){
std::cin >> points[j];
sizeofarray ++;
}
return sizeofarray;
}
int GradeCalculator::dropLowest(int* points, int size) {
int lowest = points[0];
int lowestIndex = 0;
for( int i = 0; i < size; i++ ) {
if( points[i] < lowest ) {
lowest = points[i];
lowestIndex = i;
}
}
for( int i = lowestIndex; i < size-1; i++ ) {
points[i] = points[i+1];
}
return size - 1;
}
void GradeCalculator::printResults(int* points, int size){
dropLowest(points, size);
int newtotal;
for(int k = 0; points[k] = '\0'; k++){
newtotal += points[k];
}
float avg = newtotal/size;
std::cout << "Total Points: " << newtotal << "\n" << std::endl;
std::cout << "Average: " << avg << "\n" << std::endl;
}

How to Set Int Function from Class equal to Int in Main

I have designed functions for getLength, getWidth, and getArea and I need to assign them to int values in my main function but I do not know how.
I have posted my header, implementation, and main.cpp files below.
Please adivse.
Ty.
Header File
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle
{
Rectangle();
public:
int getLength;
int getWidth();
int getArea(int x, int y)
};
#endif
Implementation File
#include "Rectangle.h"
#include <iostream>
using namespace std;
int Rectangle::getLength()
{
int x = 0;
cout << "Enter Length: ";
cin >> x;
return x;
}
int Rectangle::getWidth()
{
int x = 0;
cout << "Enter Width: ";
cin >> x;
return x;
}
int Rectangle::getArea(int x, int y)
{
int area = x * y;
return area;
}
This is where I begin running into issues. The functions return an integer, but I do not know how to be able to assign the return integer to an int value.
#include "Rectangle.h"
#include "Rectangle.cpp"
#include <iostream>
#include <vector>
using namespace std;
int main() {
int area, length, width = 0;
vector <int> myVector;
cout << "Lets Make Some Rectangles: " << endl;
for (int i = 0; i < 5; i++) {
length = Rectangle::getLength();
width = Rectangle::getWidth();
area = Rectangle::getArea(length,width);
myVector.push_back(area);
}
int largest = 0;
for (int i = 0; i < 5; i++) {
if (myVector[i] >= myVector[i + 1]) {
largest = myVector[i];
}
}
cout << "The Largest Rectangle Has an Area of: " << largest;
system("pause");
return 0;
}
One can call the member function in this way Rectangle::getLength(); only when getLength(); is declared static inside class Rectangle.
If member functions are not declared static then they can be accessed via object of the class.
Rectangle obj;
length = obj.getLength();
Also, you are crossing the valid bounds of vector myVector. You have inserted 5 elements in vector (from index 0 to 4) and trying to access 6th element myVector[5] via myVector[i] >= myVector[i + 1] when i = 4.
Correct way to find largest:
int largest = myVector[0];
for (int i = 1; i < myVector.size(); i++) {
if (largest > myVector[i]) {
largest = myVector[i];
}
}
As far as my knowledge with C++ goes, you need to create member variables which will hold the data(width, length), if you need create constructor which will take parameters for those memeber variables:
Rectangle(int width, int length){
m_width = width;
m_length = length;
}
notice member variables m_width and m_length
and create object, which will hold the data using constructor. ie
Rectangle myRectangle = Rectangle(5,5)

beginner c++ draw house program

New at c++ so if I get any terms wrong please don't ridicule me. I am trying to write a program that will draw ask the user for units and then draw house using functions. The problem that I am having is in my drawcone function Here is my progress so far.
#include<iostream>
using namespace std;
void drawcone(int height);
void drawHorizontalLine(int numXs);
void draw2VerticalLines(int numSpaces, int numRows);
void drawOneRow(int numSpaces);
void getDimensions(int& width, int& height);
void drawbox(int width, int height);
int main(){
int width;
int height;
getDimensions(height, width);
drawcone(height);
drawHorizontalLine(width);
draw2VerticalLines(width - 2, height - 2);
drawHorizontalLine(width);
return 0;
}
void drawbox(int width, int height){
drawHorizontalLine(width);
draw2VerticalLines(width - 2, height - 2);
drawHorizontalLine(width);
}
void drawcone(int height){
int base = height * 2;
int r = 0;
while ( r != height){
int c = 0;
while (c != base){
if(c==height-r || c==height+r)
cout << "X";
else
cout << " ";
c++;
}
cout << endl;
r++;
}
}
void drawHorizontalLine(int numXs)
{
int count;
for (count = 0; count < numXs; count++){
cout << "X";
}
cout << endl;
}
void draw2VerticalLines(int numSpaces, int numRows)
{
int rowCount;
for (rowCount = 0; rowCount < numRows; rowCount++){
drawOneRow(numSpaces);
}
}
void drawOneRow(int numSpaces)
{
int spaceCount;
cout << "X";
for (spaceCount = 0; spaceCount < numSpaces; spaceCount++){
cout << " ";
}
cout << "X" << endl;
}
void getDimensions(int& width, int& height){
cout << "Enter the width of the house" << endl;
cin >> width;
cout << "Enter the height of the house" << endl;
cin >> height;
}
The correct sample output would look like this
X
X X
X X
XXXXX
X X
X X
XXXXX
My current output looks like this
X
X X
X X
X X
XXXX
X X
X X
XXXX
I would like the cone to be slightly smaller so it will be proportionate to the box. I would also prefer an answer that does not involve modifying the drawbox function. Thank you for your time!
Here's one solution. However, the cone will be symmetrical only if the width is odd.
#include<iostream>
using namespace std;
void drawcone(int height);
void drawHorizontalLine(int numXs);
void draw2VerticalLines(int numSpaces, int numRows);
void drawOneRow(int numSpaces);
void getDimensions(int& width, int& height);
void drawbox(int width, int height);
int main() {
int width;
int height;
getDimensions(width, height);
drawcone(width);
drawHorizontalLine(width);
draw2VerticalLines(width - 2, height - 2);
drawHorizontalLine(width);
return 0;
}
void drawbox(int width, int height) {
drawHorizontalLine(width);
draw2VerticalLines(width - 2, height - 2);
drawHorizontalLine(width);
}
void drawcone(int width) {
for (int i=0; i<(width/2 + width%2); i++) {
for (int j=width/2-i; j>0; j--) {
cout << " ";
}
drawOneRow(i*2-1);
}
}
void drawHorizontalLine(int numXs)
{
int count;
for (count = 0; count < numXs; count++) {
cout << "X";
}
cout << endl;
}
void draw2VerticalLines(int numSpaces, int numRows)
{
int rowCount;
for (rowCount = 0; rowCount < numRows; rowCount++) {
drawOneRow(numSpaces);
}
}
void drawOneRow(int numSpaces)
{
int spaceCount;
cout << "X";
if (numSpaces > 0) {
for (spaceCount = 0; spaceCount < numSpaces; spaceCount++) {
cout << " ";
}
cout << "X";
}
cout << endl;
}
void getDimensions(int& width, int& height) {
cout << "Enter the width of the house" << endl;
cin >> width;
cout << "Enter the height of the house" << endl;
cin >> height;
}
Should be fairly easy to debug, it's printing out the wrong number of spaces for the 'roof' of the house.
The problem should be contained in the while ( r != height) block
try messing with the else {cout << " ";} with else if(c%2==1){cout << " ";}
#include<iostream>
using namespace std;
void roof(int height);
void hLine(int num);
void vLine(int spaces, int rows);
void row(int spaces);
void dimensions(int& width, int& height);
void box(int width, int height);
int main()
{
int width;
int height;
dimensions(height, width);
roof(height);
hLine(width);
vLine(width - 2, height - 2);
hLine(width);
return 0;
}
void box(int width, int height)
{
hLine(width);
vLine(width - 2, height - 2);
hLine(width);
}
void roof(int height)
{
int base = height * 2;
int r = 0;
while ( r != height)
{
int c = 0;
while (c != base)
{
if(c==height-r || c==height+r)
cout << "*";
else
cout << " ";
c++;
}
cout << endl;
r++;
}
}
void hLine(int num)
{
int count;
for (count = 0; count < num*2+1; count++)
{
cout << "-";
}
cout << endl;
}
void vLine(int spaces, int rows)
{
int numrows;
for (numrows = 0; numrows < rows; numrows++)
{
row(spaces);
}
}
void row(int spaces)
{
int numspaces;
cout << "{";
for (numspaces = 0; numspaces < spaces*2+3; numspaces++)
{
cout << "$";
}
cout << "}" << endl;
}
void dimensions(int& width, int& height)
{
cout<<"Enter the width of the house"<<endl;
cin>>width;
cout<<"Enter the height of the house"<<endl;
cin>>height;
}

C++ Turning arrays into functions?

I have been attempting this for hours to no avail, as you can see in my code I have separate functions, they were all together in main, but I am required to turn each into a separate function. However when I try anything I get errors, even when I try to pass parameters. Can someone point me in the right direction?
#include <iostream>
#include <cstdlib>
#include <ctime>
void printarray();
void average();
void largestnumber();
using namespace std;
int main()
{
printarray();
average();
largestnumber();
}
void printarray() {
srand(time(0));
int n[10], tot = 0;
for (int i = 0; i < 10; i++)
{
n[i] = (1 + rand() % 100);
cout << n[i] << endl;
}
}
void average() {
int j, tot = 0, n[10];
for (j = 0; j < 10; j++)
{
tot += n[j];
}
cout << "The average of the numbers in the array are " << tot / j << endl;
}
void largestnumber() {
int w = 1, int n[10];
int temp = n[0];
while (w < 10)
{
if (temp < n[w])
temp = n[w];
w++;
}
cout << "The largest number in the array is " << temp << endl;
}
The array you are working with needs to be passed in to each function, so the same array is used everywhere. It is a good idea to pass the size as well, just for flexibility reasons.
Now your functions pretty much work as you wrote them.
#include <iostream>
#include <cstdlib>
#include <ctime>
void printarray(int n[], size_t size);
void average(int n[], size_t size);
void largestnumber(int n[], size_t size);
using namespace std;
int main()
{
const size_t arr_size = 10;
int n[arr_size];
printarray(n, arr_size);
average(n, arr_size);
largestnumber(n, arr_size);
}
void printarray(int n[], size_t size) {
srand((unsigned int)time(0));
int tot = 0;
for (size_t i = 0; i < size; i++)
{
n[i] = (1 + rand() % 100);
cout << n[i] << endl;
}
}
void average(int n[], size_t size) {
size_t j;
int tot = 0;
for (j = 0; j < size; j++)
{
tot += n[j];
}
cout << "The average of the numbers in the array are " << tot / j << endl;
}
void largestnumber(int n[], size_t size) {
size_t w = 1;
int temp = n[0];
while (w < size)
{
if (temp < n[w])
temp = n[w];
w++;
}
cout << "The largest number in the array is " << temp << endl;
}
One simple improvement is to break the printarray out into an initarray function that fills the array and printarray that prints the content.
It would also be a good idea to do some checking for things like an empty array (functions assume n[0] exists, for instance).
The next obvious step is to put all this in a class. Also, if you are allowed to, the c array should be replaced with a vector, as that does a great job of keeping all the resource information together.

Adding a random member from an array of chars to a game board in C++

I am programming a game for a university project and i am having a little trouble with it. So here is my game board class header file:
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstdio>
#include <time.h>
class CMagicAlchemistBoard
{
public:
CMagicAlchemistBoard(void); // Default Constructor
CMagicAlchemistBoard(const CMagicAlchemistBoard& board); // Copy Constructor
~CMagicAlchemistBoard(void ); // Destructor
void SetupBoard(void); // Function to setup the board
int GetBoardSpace(int row, int col); // Get the color at row,col
// Accessor functions to get/set board size information
int GetColumns(void) const { return m_nColumns; }
void SetColumns(int nColumns) { m_nColumns = (nColumns >= 6) ? nColumns : 6; }
int GetRows(void) const { return m_nRows; }
void SetRows(int nRows) { m_nRows = (nRows >= 8) ? nRows : 8; }
void DeleteBoard(void); // Function to delete the board and free memory
void ExecuteMove(int row, int col);
bool IsGameOver(void) const; // Is the game over?
void DrawBoard(void);
bool ValidMove(int row, int col); // Function to see if a move is valid
char RandomPiece();
private:
void CreateBoard(void); //Function to create the board and allocate memory
// Class Data
int** m_arrBoard; // 2D array pointer
// Board size information
char m_arrChars[20];
int m_nColumns;
int m_nRows;
};
And here are the important parts of the game board .cpp file:
#include "cmagicalchemistboard.h"
using namespace std;
CMagicAlchemistBoard::CMagicAlchemistBoard(void)
: m_arrBoard(NULL), m_nColumns(6), m_nRows(8)
{
m_arrChars[0] = ' ';
}
CMagicAlchemistBoard::CMagicAlchemistBoard(const CMagicAlchemistBoard& board)
{
// Copy all of the regular data members
m_nColumns = board.m_nColumns; m_nRows = board.m_nRows;
m_arrBoard = NULL;
CreateBoard(); // Create a new game board of the same size
// Copy the contents of the game board
for(int row = 0; row < m_nRows; row++)
for(int col = 0; col < m_nColumns; col++)
m_arrBoard[row][col] = board.m_arrBoard[row][col];
int CMagicAlchemistBoard::GetBoardSpace(int row, int col)
{
if(row<0 || row>=m_nRows || col<0 || col>=m_nColumns) return 0;
return m_arrBoard[row][col];
}
void CMagicAlchemistBoard::CreateBoard(void)
{
// If there is already a board, delete it
if(m_arrBoard != NULL) DeleteBoard();
// Create the array of rows
m_arrBoard = new int*[m_nRows];
// Create each row
for(int row = 0; row < m_nRows; row++){
m_arrBoard[row] = new int[m_nColumns];
// Set each square to be empty
for(int col = 0; col < m_nColumns; col++)
m_arrBoard[row][col] = 0;
}
}
void CMagicAlchemistBoard::DrawBoard(void)
{
cout << "MAGIC ALCHEMIST" << endl;
cout << " ";
for(int col = 0; col < m_nColumns; col++){ printf(" ---",col); }
cout << endl;
for(int row = 0; row < m_nRows; row++)
{
for(int col = 0; col < m_nColumns; col++)
{
// printf("| %c", m_arrChars[0]);
cout << "| " << m_arrChars[0];
}
cout << "| " << endl;
}
}
So my idea is to have a function that will add one random char between 12 chars to m_arrBoard[0][2] position. Can someone help me with this please?
Create a function that returns a random character out of 12 predefined
characmters. Call it to assign a random character to m_arrBoard[0][2].
// The function to get a random character.
char getRandomChar()
{
char arr[12] = {}; // Initialize the array of characters.
int index = rand()%12;
return arr[index];
}
Somewhere down in some function....
// Assign a random character to m_arrBoard[0][2].
m_arrBoard[0][2] = getRandomChar();
Let's say you want to receive random characters from A to Z. You can try the following code:
std::vector<char> arr;
int n = (90-65 +1);//'Z'-'A'
int movePosition = 65;
for (unsigned int i = 0; i < 12; ++i)
{
int number = rand() % n;//Get a number from 0 to n-1 (where n is 26)
std::cout << "number = " << number << "; movePosition = " << movePosition << std::endl;
// To get a letter add movePosition to it so you are back in the range of 65 to 90
arr.push_back((char)(number + movePosition));
}
To see what characters you have added, you can try the following:
for (int i = 0;i<arr.size();i++)
{
std::cout << "Char=" << arr[i] << std::endl;
}