Reputation: 147
struct node {
int key;
struct node* left;
struct node* right;
};
struct node * newBST(int key){
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp -> key = key;
temp -> left = temp -> right = NULL;
return key;
}
So I am unable to understand why we malloc the size of node? to struct *temp ? Is it so we can access the elements created in the node ?
Upvotes: 0
Views: 44
Reputation: 198314
To reserve the memory. After struct node {...}
, you basically now have a blueprint on how nodes are supposed to look like. Then you go to the urban memory planning office, and tell them "I'm making a new node, can I reserve 24 square meters bytes somewhere?" And they tell you "Sure, this here should be a good place, we promise not to give it to anyone else. Just make sure not to mess with anything outside those 24 square meters bytes, or bad things will happen". So you take your temp
address, go there and start laying out stuff: key
goes in these 8 square meters bytes, and let's clean these 8 and these other 8 from all the cruft that may have been there before...
*) int
nowadays usually takes up 8 bytes of memory, and each pointer does as well. But this is dependent on your computer and compiler.
Upvotes: 4