Van Teo Le
Van Teo Le

Reputation: 156

pointers don't change after i modified it

I'm setting up a struct called Node

    typedef struct node{
struct node *left;
struct node *right;
struct node *parent;
    }node;

and a function that operate on the nodes:

   int test(node *old,node* new){
old->parent->right = new;
new->parent = old->parent;
    }

Ok, so i make 3 nodes and set up the relationship between them

node* me =malloc(sizeof(node));
node* me1 = malloc(sizeof(node));
node* me2 = malloc(sizeof(node));
me->right = me1;
me->left = me2;
me1->parent = me;
me2->parent = me;
test(me1,me);

1.However, after test(), me1->parent->right changed while me1 didn't, which is weird because me1 and me1->parent->right point are the same address. I wonder if i make any wrong assumption here?

2.In function test(), if i replace old->parent->right with old only, then after the function call, the node me1 remains the same. Isn't the pointer modified after we do operations on it inside a function,and why in this case it is not?

Upvotes: 0

Views: 53

Answers (2)

Erlkoenig
Erlkoenig

Reputation: 2754

me, me1, and me2 are local variables inside your outer function (let's assume it was main). These pointers are never modified, so after the call to test, me1 still points to the same node as before, while the pointer me1->parent->right now points to me. So, "me1 and me1->parent->right point are the same address" isn't true anymore!

If you only modify old inside test, you will only modify the parameter old, which is a copy of me1. After test returns, this copy is forgotten, and the modification has no effect. If you want to modify the me1 variable from within test, you will have to pass a pointer to the pointer, i.e. a double pointer:

int test(node **old,node* new){
  *old = new;
  ...
}

and call it as test(&me1,me);.

Also: Please don't name things "new", because if you ever decide to compile the code as C++, this will conflict with the reserved keyword new.

Upvotes: 1

Afshin
Afshin

Reputation: 9173

Here is what your test() method does:

int test(node *old,node* new){
    old->parent->right = new;
    new->parent = old->parent;
}

when you call this:

me->right = me1;
me1->parent = me;
test(me1,me);

These steps happens:

  1. me1's parent is me and me's right is me1. So me's right becomes me again.
  2. me's parent becomes me itself.

Upvotes: 0

Related Questions