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)
{
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
NODEALLOCand 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 becomesroot=(struct treenode*)malloc(sizeof(struct treenode))malloc(n)allocates n bytes of memory,sizeoftells malloc how bignneeds to be, and(struct treenode*)casts malloc’s returnedvoid*into the correct type.