I have a binary tree and a struct with three tree pointers and a void pointer for the key of the node.When trying to insert a node,even though the key gets the value that it is expected,then when i set the tree pointers to NULL,the left pointer seems to overwrite the void pointer and as a result i get a key equal to zero always!
The insertion function
Code:
Treeptr addtree(Treeptr p, void* v ,int sizeOfType,int (*compare)
( void* arg1, void* arg2))
/* Insert value v into tree p */
{
Treeptr y = NULL;
Treeptr x = p;
/* Allocate space for new node */
Treeptr z = malloc(sizeof(Treeptr));
printf("The value inside the function %d\n",*(int*)v);
z->value = malloc(sizeOfType); /* Allocate memory for value */
memcpy( z->value , v , sizeOfType ); /* Copy value */
printf("The value of node BEFORE setting the pointers to null %d\n",*(int*)z->value);
z->left = NULL;
z->right = NULL;
z->parent = NULL;
printf("The value of node AFTER setting the pointers to null %d\n",*(int*)z->value);
while(x != NULL) {
y = x;
if( compare(z->value,x->value) == -1 )
x = x->left;
else
x = x->right;
}
z->parent = y;
if(y == NULL) {
p = z;
}
else if( compare(z->value,y->value) == -1 ) {
y->left = z;
}
else {
y->right = z;
}
return p;
}
My struct
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tnode *Treeptr;
typedef struct tnode {
Treeptr left;
Treeptr parent;
Treeptr right;
void* value;
} Treenode;
Treeptr addtree(Treeptr p, void* v ,int sizeOfType,int (*compare)
( void* arg1, void* arg2));
void nodesGeneric(Treeptr,void(*)(void*));
Treeptr minnode(Treeptr p);
Treeptr successor(Treeptr x);
Treeptr treesearch(Treeptr p, void* v);
Treeptr deletenode(Treeptr p ,void* v);
The main
Code:
int main(void)
{ Treeptr p;
char answer;
void* v;
int value,n,i;
p = NULL; /* Initialize binary tree */
printf("Please insert number of nodes of the tree\n");
scanf("%d",&n);
if(n < 1)
{
printf("\nValue less than one inserted.Exiting...\n");
return -1;
}
printf("Please insert nodes of tree.\n");
for( i = 0 ; i < n ; i++ ) {
scanf("%d", &value); /* Read values from input */
v = &value; /* and insert them into the tree */
p = addtree(p, v , sizeof(int) , int_sorter);
}
.....
return 0;
}
I tried to play around with the position of the pointers,where i set them to null and where they are placed inside the struct,but again i had the same problem.Actually once i got a segmentation fault...What is the problem?