Reputation: 1
I found this code (C code) about a maze generator and i would like to use it in C++ :
{
int x, y; //Node position - little waste of memory, but it allows faster generation
void *parent; //Pointer to parent node
char c; //Character to be displayed
char dirs; //Directions that still haven't been explored
} Node;
Node *nodes; //Nodes array
int width, height; //Maze dimensions
int init( )
{
int i, j;
Node *n;
//Allocate memory for maze
nodes = calloc( width * height, sizeof( Node ) );
if ( nodes == NULL ) return 1;
//Setup crucial nodes
for ( i = 0; i < width; i++ )
{
for ( j = 0; j < height; j++ )
{
n = nodes + i + j * width;
if ( i * j % 2 )
{
n->x = i;
n->y = j;
n->dirs = 15; //Assume that all directions can be explored (4 youngest bits set)
n->c = ' ';
}
else n->c = '#'; //Add walls between nodes
}
}
return 0;
}
the problem comes frome the line nodes = calloc( width * height, sizeof( Node ) );
How can i change it for a C++ code? I would like as possible to avoid to use new
as all the code is big.
Upvotes: 0
Views: 219
Reputation: 211680
This is C++ so set calloc
aside and use new[]
:
Node *n = new Node[width * height];
Even better, std::vector
:
std::vector<Node> n(width * height);
Where in both cases it's as easy as:
auto& node = n[i + j * width];
To access individual elements.
You'll also want to make a proper constructor for your Node
that sets up those pointers, or at least gives them safe defaults. In that case it might be easier to add them to the vector as you go, like:
std::vector<Node> n; // Start empty
// Inside the loops...
n.emplace_back(i, j, nullptr, ' ', 15);
Upvotes: 1