the code is:
int main(int argc, const char* argv[] )
{
struct node * initialpointer=NULL;
insert("asd", initialpointer, 1);
if(initialpointer!=NULL)
printf("isnotnull");
if (initialpointer==NULL)
printf("isnull");
}
insert(char* x,struct node * initialpointer, int numberofelements){
struct node B;
B.word = x;
B.parent = NULL;
B.leftchild = NULL;
B.rightchild = NULL;
printf("%d", 12);
if ( initialpointer == NULL){
initialpointer = &B;
B.parent = NULL;
}
}
So in the end I want initialpointer to point where nde B is but in the main method it prints it is null. So how can I change the initialpointer in function insert permanently?
There are a couple problems with your code.
First is the problem you’re having. The pointer you’re passing to
insertis passed by copy; the function gets a copy andmaindoesn’t see your change. The solution to this is to pass a pointer to the pointer. See the POSIX functionstrtolfor a standard library example of how this looks.The second problem is that you’re returning a pointer to a local, automatic (i.e. stack-allocated) variable. Since the stack is released on function exit, this pointer points to invalid memory when it is back in
main. So instead you need to allocateBfrom the heap.So, fixing things up: