(Note: I’m currently learning C++, so if there is a better way to do what I am doing, explanations would be helpful.)
I am making Conway’s Game of Life in C/C++ and have the following code:
bool ** previous;
bool ** current;
void init() {
previous = new bool*[width];
current = new bool*[width];
for (int i =0; i < width; i++) {
previous[i] = new bool[height];
current[i] = new bool[height];
}
}
The reason for the dynamic arrays is that the width and height are given by the user at runtime. If I had one-dimensional arrays, I could do the following:
bool * previous;
bool * current;
void () {
bool * temp = current;
current = previous;
previous = temp;
}
However, this approach does not work as hoped with the two-dimensional array. As it is technically an array of arrays, do I have to swap each sub-array pointer individually? Is there a better way to go about defining multi-dimensional arrays and swapping them?
Edit: I have yet to really use any C++ specific features, so if I can do this in pure C, I’d prefer that.
There’s no real reason here to bother with an array of arrays. It’s a ton more work to maintain and destroy properly, especially as you’ve avoided using the Standard Library containers that would handle a lot of the memory management for you.
It’s usually easier to allocate
width * heightcells in a single array and reference them likecell[x + width * y]wherexis your column,yis your row.Do keep in mind that in the particular case of this problem what you want is an array of bits and not an array of booleans. C++ does have a special case container for a bitset that is worth using:
std::vector<bool>.