S
sathyashrayan
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct tree
{
int data;
struct tree *left,*right;
};
void init(struct tree *node)
{
node = malloc(sizeof node);
if(!node)
{
printf("mem error\n");
exit(EXIT_FAILURE);
}
}
struct tree *assign(int data,struct tree *node)
{
struct tree *temp;
memmove(temp,node,sizeof node);
init(temp);
temp->data = data;
if(data < temp->data)
{
temp = temp->left;
temp->data = data;
}
else if(data > temp->data)
{
temp = temp->right;
temp->data = data;
}
else
temp->right = temp->left = NULL;
memmove(node,temp,sizeof node);
return node;
}
int print_tree(struct tree *node)
{
printf("%d\n",node->data);
while(node != NULL)
{
struct tree *temp;
memmove(temp,node,sizeof node);
temp = temp -> right;
print_tree(temp);
temp = temp-> left;
memmove(node,temp,sizeof node);
}
return 0;
}
int main(void)
{
struct tree *node;
node = assign(1 , node);
node = assign(2 , node);
node = assign(8 , node);
print_tree(node);
return 0;
}
This little, ugly code does not work as expected. I am getting a memory
overflow error. What could be the problem? Help.
--
"combination is the heart of chess"
A.Alekhine
Mail to:
sathyashrayan AT gmail DOT com
#include<stdlib.h>
#include<string.h>
struct tree
{
int data;
struct tree *left,*right;
};
void init(struct tree *node)
{
node = malloc(sizeof node);
if(!node)
{
printf("mem error\n");
exit(EXIT_FAILURE);
}
}
struct tree *assign(int data,struct tree *node)
{
struct tree *temp;
memmove(temp,node,sizeof node);
init(temp);
temp->data = data;
if(data < temp->data)
{
temp = temp->left;
temp->data = data;
}
else if(data > temp->data)
{
temp = temp->right;
temp->data = data;
}
else
temp->right = temp->left = NULL;
memmove(node,temp,sizeof node);
return node;
}
int print_tree(struct tree *node)
{
printf("%d\n",node->data);
while(node != NULL)
{
struct tree *temp;
memmove(temp,node,sizeof node);
temp = temp -> right;
print_tree(temp);
temp = temp-> left;
memmove(node,temp,sizeof node);
}
return 0;
}
int main(void)
{
struct tree *node;
node = assign(1 , node);
node = assign(2 , node);
node = assign(8 , node);
print_tree(node);
return 0;
}
This little, ugly code does not work as expected. I am getting a memory
overflow error. What could be the problem? Help.
--
"combination is the heart of chess"
A.Alekhine
Mail to:
sathyashrayan AT gmail DOT com