1

I'm trying to import some c code into my c++ program. There are three lines that don't import directly:

The first:

free(t);

The second:

new_node = (Tree *) malloc (sizeof (Tree));

The third:

Tree * delete(int value, Tree * t)

How can these be changed to work in C++?

1
  • 1
    Error message are really awesome. Otherwise we are all just guessing. One note is delete is a keyword in c++
    – rerun
    Feb 11, 2010 at 5:00

3 Answers 3

5

You can use free and malloc in C++. Whether you should is a different story, but if you're porting a C library the answer to that is yes (at least for now).

delete is a keyword in C++, you will need to rename that function.

4

Assuming you want convert it to C++ style new/delete (see other answers about continuing to use malloc/free):

// 1. free(t);
delete t;

// 2. new_node = (Tree *) malloc (sizeof (Tree));
new_node = new Tree;

// 3. Tree * delete(int value, Tree * t)
Tree * delete_tree(int value, Tree* t)

Note: for #3, you will need to change all users of delete(value, t) to delete_tree(value, t).

2

The first two lines should be valid C++, assuming you've included stdlib.h, and have defined Tree as a class/struct/type somewhere.

The third line will need to be changed, since 'delete' is a keyword in C++ and can't be used as a function name. Try doing a global replace in the C code and changing all instances of 'delete' with 'delete_from_tree' or something like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.