Good day, I just started to learn void pointers in c++ and now I'm writing binary tree where value stored in each node is void pointer to a value.
struct TreeNode
{
int count;
void* data;
TreeNode *left;
TreeNode *right;
};
The problem occurred in very first method-add method. my method now takes int a a parameter and return nothing At the very beginning i create new node. To do that I need to cast integer into void. Program compiles and first element adds to root correctly-however then when i send another number to method it stores in root again. so if in main i have something like tree.addToTree(12); tree.addToTree(13); than it would store 12 first and than right after else statement(code below)how that root->data i 13.
void Tree::addToTree(int num)
{
if(root==NULL){
root= new TreeNode();
root->data=#
//((int *)(root->data)) = num;//i tried to convert to void* in this way but it give me segmentation fault
root->left=NULL;
root->right=NULL;
}
else{
//here root value is already changed
int *intPtr = static_cast<int*>(root->data);
cout << "key2" << *intPtrT << endl;
//TreeNode* current= insert(num,root);
}
}
as i understood thats because i use &num so my parameter always tore in one place and a root is "connected" to &num it change as well.
I tried to find solution but was unsuccessful. Is there a way to cat int to void pointer?
((int *)(root->data)) = numcan't compile. Would have to be((int *)(root->data)) = &numor*((int *)(root->data)) = num. Which one was it? - user3458