I recently finished "The C Programming Language - 2nd Edition" and I thought a good next step would be creating my own data structures library using C.
I'm currently working on implementing a standard binary tree and I've been stuck with the insertion method. So far I've created the node struct:
typedef struct node
{
int data;
struct node * rc;
struct node * lc;
}NODE;
and I'm trying to get insertion method to work when presented with the root node of the tree. Here is how I've created the root node and how I call it in the addNode() function:
int main() {
NODE * root = NULL;
addNode(12, root);
return 0;
}
My addNode() function is structued like so:
void addNode(int info, NODE * node)
{
if (node == NULL) {
node = (NODE *)malloc(sizeof(NODE));
node->data = info;
node->rc = NULL;
node->lc = NULL;
}
}
When I try to display the actual value of 'data' stored within the NODE * root from the main method, I get a segmentation fault. After some exploring, I realized that the reason for this was that my memory allocation for node in the addNode() method was not actually redefining root to be newly allocated memory with the value 'info' but was instead creating a separate NODE * node.
Ultimately I think my issue is that I'm still trying to grasp pointers in C but I would greatly appreciate any insight into how I could go about fixing my code. (Sorry in advance if my C terminology is not quite there yet either)