I'm currently making a RedBlackTree in C and I still don't understand which one is better / more ideal when it comes to having a constuctor function for your structures.
struct RedBlackTree* RedBlackTree_new()
{
struct RedBlackTree *tree = calloc(1, sizeof(struct RedBlackTree));
if (tree == NULL)
error(DS_MSG_OUT_OF_MEM);
return tree
}
VS.
struct RedBlackTree RedBlackTree_new()
{
struct RedBlackTree tree;
tree.root = NULL;
tree.size = 0;
return tree;
}
I mean, if I do the second option, then I constantly have to pass it into my functions as a pointer using &
and to my knowledge, I can never destroy it until my program ends (can someone verify if that's true?). For example, if I had adestroy
function for my Tree, I wouldn't be able to free the memory allocated from structures within the RedBlackTree
if they weren't created with malloc
or calloc
right?
Also in a more general case, what are the advantages and disadvantages of either? I can always retrieve the data from the pointer by using *
and I can always turn my data into a pointer by using &
, so it almost feels like they are completely interchangable in a sense.