Reputation: 119
I am changing a path planning code from C to C++. The code dynamically allocates the states in map. I don't clearly understand the difference between new
and malloc
. I get an error for following snippet of code.
typedef struct cell
{
int x,y;
struct cell *n[5];
}cell_t;
typedef struct pq
{
cell_t **heap;
int len,cap;
}pq_t;
//for C version
func(pq_t *pq,50)
{
pq->heap = malloc(sizeof(cell)*50);
pq->len = 0;
pq->cap = 0;
}
//for C++ version
func(pq_t *pq,50)
{
pq->heap = (cell_t*)::operator new(sizeof(cell_t)*50);
pq->len = 0;
pq->cap = 0;
}
The error I get is :
cannot convert ‘
cell_t
* {akacell*
}’ to ‘cell_t**
{akacell_s**
}’ in assignmentpq->heap =(cell_t*) ::operator new (sizeof(cell_t) * (50));""
What do I need to change?
Upvotes: 4
Views: 134
Reputation: 36082
new takes the type or an array of types, the size is then calculated i.e.
cell_t* p = new cell_t // allocate one cell
cell_t* p = new cell_t[50] // allocate 50 cells.
However I think you would be much better off with using one of the standard containers in your program like std::vector
#include <vector>
..
std::vector<cell_t> myarray(50); // allocate 50 cell_t
then you do not need to concern yourself with freeing the memory, std::vector handles that for you.
Upvotes: 4
Reputation: 249143
Instead of this:
pq->heap = (cell_t*)::operator new(sizeof(cell_t)*50);
You want this:
pq->heap = new cell_t[50];
That said, it's clear that the code you've posted is not quite your real code, so there could be some additional mistake in there. Maybe update your question with real code that compiles.
Upvotes: 8