I’m trying to code a Bingo Board in C++, but I’m doing something very wrong. I’m not sure what, but for whatever reason when I initialize the number of rows and columns, and do a nested for loop on the arrays I created to implement this structure, I get what appears to be more than a hundred rows and 30+ columns, when I should just be getting a five, by five board. I’m also trying to specify a max and min value for my rand function, but it appears that there isn’t a way to do this. Thus, what would be the best approach to accomplish this without giving away the solution? The reason why I mention that last bit is so I can learn how to do this lol.
Here is my code:
#ifndef BOARD_H
#define BOARD_H
#include <cstdlib>
#include <time.h>
#include <stdio.h>
class Board
{
public:
Board(unsigned int numberOfRows, unsigned int numberOfColumns, unsigned int seed, unsigned int max, unsigned int min);
void generate();
void setSeedValue(int seed);
private:
unsigned int m_rows[];
unsigned int m_columns[];
unsigned int m_max, m_min;
};
#endif // BOARD_H
Board::Board(unsigned int numberOfRows, unsigned int numberOfColumns, unsigned int seed, unsigned int max, unsigned int min)
{
this->m_rows[numberOfRows];
this->m_columns[numberOfColumns];
srand(seed);
this->m_max = max;
this->m_min = min;
printf("%d\n", size_t(m_rows));
printf("%d\n", size_t(m_columns));
}
void Board::generate()
{
for (int i = 0; i < size_t(m_rows); i++)
{
for(int j = 0; j < size_t(m_columns); j++)
{
this->m_columns[j] = (rand() % 10) + j;
std::cout << this->m_columns[j];
}
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Board * board = new Board(5, 5, time(NULL), 100, 1);
board->generate();
delete board;
return a.exec();
}
In order to create the 2-dimensional board your wanting, where the size is input at runtime, you’re going to have to actually dynamically allocate a board in memory … you can’t declare your board the way you’ve done in your class as zero-length arrays.
Code like this:
does not initialize your array-size … rather it actually attempts to access memory allocated at that offset from the start of
m_rows… that could cause a segmentation fault or some other undefined behavior due to accessing memory beyond the end of the class/structure type.It would be much better, since you’re using C++, to create your board class using the STL’s
std::vectorcontainer. YourBoardclass would then look like the following:Then in your constructor, you would actually allocate the necessary memory (through the STL’s vector container) that your board will take up:
Finally, your
Board::generatefunction would now look like the following: