Hi all,
I have been trying to access an element in a dynamically allocated struct. The problem is that it either will not compile, or return a seg fault when it reached the line of code in bold. I have changed that line of code to everything I can think of, using ()'s, *'s, &'s, ->'s, and .'s and nothing so far has worked. Any help is appreciated. Also, how would I go about initializing frequency to 0 upon creation of the struct?
typedefstruct node{
string data;
int frequency;
node *left;
node *right;
};
void btree::insert(string key, node *leaf)
{
if(key< leaf->data)
{
if(leaf->left!=NULL)
insert(key, leaf->left);
else
{
leaf->left=new node;
leaf->left->data=key;
leaf->left->left=NULL; //Sets the left child of the child node to null
leaf->left->right=NULL; //Sets the right child of the child node to null
}
}
elseif(key>=leaf->data)
{
if(leaf->right!=NULL)
insert(key, leaf->right);
else
{
leaf->right=new node;
leaf->right->data=key;
leaf->right->left=NULL; //Sets the left child of the child node to null
leaf->right->right=NULL; //Sets the right child of the child node to null
}
}
}
void btree::insert(string key)
{
node *temp=search(key);
if(temp==NULL) //If the string is not present already
{
if(root!=NULL)
insert(key, root);
else
{
root=new node;
root->data=key;
root->left=NULL;
root->right=NULL;
}
}
(temp)->frequency++;
}
/*typedef*/struct node{ // typedef is used in C programs in notation typedef struct
// { string data; ... } node; to avoid using keyword struct
// before struct object declaration, because in C structs are
// not types. In C++ such a notation is unnecessary.
string data;
int frequency;
node *left;
node *right;
};
void btree::insert(string key, node *leaf)
{
if(key< leaf->data)
{
if(leaf->left!=NULL)
insert(key, leaf->left);
else
{
leaf->left=new node;
leaf->left->data=key;
leaf->left->left=NULL; //Sets the left child of the child node to null
leaf->left->right=NULL; //Sets the right child of the child node to null
}
}
elseif(key>=leaf->data)
{
if(leaf->right!=NULL)
insert(key, leaf->right);
else
{
leaf->right=new node;
leaf->right->data=key;
leaf->right->left=NULL; //Sets the left child of the child node to null
leaf->right->right=NULL; //Sets the right child of the child node to null
}
}
}
void btree::insert(string key)
{
node *temp=search(key);
if(temp==NULL) //If the string is not present already
{
if(root!=NULL)
insert(key, root);
else
{
root=new node;
root->data=key;
root->left=NULL;
root->right=NULL;
}
}
else // if temp is not NULL
temp->frequency++; // everything here is right
}
(temp)->frequency++; still crashes the program. However, the code you gave me does initialize the value (at least it doesn't crash the program?), so thank you for that. How would I go about changing the value?