how to create tree using # define
I want to create a tree. I saw the following code
#define NODEALLOC(struct treenode*)malloc(sizeof(struct treenode))
struct treenode{
int data;
struct treenode * left;
strruct treenode *right;
}
typedef struct treenode *treeptr;
treeptr root;
treeptr create(int d)开发者_JS百科
{
treeptr root;
root =NODEALLOC;
root->data=d;
root->left=null;
root->right=null;
return root;
}
I am not understanding the #define
statement.can anyone help me?
First, it's wrong, it needs a space between the NODEALLOC
and the (
Second, it's evil. There are good uses for macros; this is not one of them.
Here's how it works:
It's a simple string substitution, so when you see root=NODEALLOC;
it becomes root=(struct treenode*)malloc(sizeof(struct treenode))
malloc(n)
allocates n bytes of memory, sizeof
tells malloc how big n
needs to be, and (struct treenode*)
casts malloc's returned void*
into the correct type.
Don't use that. Use a function if you don't wan't to write the malloc
more than once. Using macros like this is something you should better avoid (it's legal, but not considered a good practice).
If you don't know what macros are in the first place, read.
It's simple. Replace NODEALLOC in code with its definition. In your case:
treeptr create(int d)
{
treeptr root;
root = (struct treenode*)malloc(sizeof(struct treenode)); // was NODEALLOC;
root->data=d;
root->left=null;
root->right=null;
return root;
}
Thus, this is a simple allocation.
However, using a macro only for this is not really helpful, it can even confuse readers of your code. Usually, a macro should do something useful.
精彩评论