Malloc to C++ version

I cannot figure out how to change this C code:

curr=(struct node*)malloc(sizeof(struct node));

to C++. It will not run in the terminal and this is the alternative that I have come up with which doesn't work:

curr= struct node*;

Thanks for any help!



curr=new node;

But seriously, get yourself a book about C++.
Last edited on
Actually, that's legal C++ if you include cstdlib (which you'd have to do with C too, except it's called stdlib.h there). Not good C++, but C++ nevertheless.
> I cannot figure out how to change this C code:
> curr=(struct node*)malloc(sizeof(struct node));

The best option is the one already given by Athar.

A verbatim translation to C++ would be
1
2
3
#include <cstdlib>
// ...
curr = (node*)std::malloc( sizeof(node) );


Or, better:
1
2
3
#include <cstdlib>
// ...
curr = static_cast<node*>( std::malloc( sizeof(node) ) ) ;

Awesome, that works! thanks!

Actually, that's legal C++ if you include cstdlib (which you'd have to do with C too, except it's called stdlib.h there). Not good C++, but C++ nevertheless.


hanst, what's wrong with that allocation method? That's how I used to do it back in 85.
Last edited on
malloc doesn't call ctors. free doesn't call dtors.

In C++ you're better off using new/delete.
Thank you, Disch. I wasn't aware of that. I've been using new/delete simply for "completeness" of my C++ education.
Topic archived. No new replies allowed.