Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing malloc to new operator

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* {aka cell*}’ to ‘cell_t** {aka cell_s**}’ in assignment

pq->heap =(cell_t*) ::operator new (sizeof(cell_t) * (50));""

What do I need to change?

like image 640
Karthi13 Avatar asked Dec 14 '22 06:12

Karthi13


1 Answers

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.

like image 196
John Zwinck Avatar answered Dec 28 '22 14:12

John Zwinck