[英]pointers don't change after i modified it
I'm setting up a struct called Node 我正在建立一个名为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 好,所以我建立了3个节点并建立了它们之间的关系
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. 1.但是,在test()之后,me1-> parent-> right改变了而me1没有改变,这很奇怪,因为me1和me1-> parent-> right点是相同的地址。 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. 2.在函数test()中,如果我仅用old替换old-> parent-> right,则在函数调用后,节点me1保持不变。 Isn't the pointer modified after we do operations on it inside a function,and why in this case it is not? 在函数内部对指针进行操作后,指针是否未修改?为什么在这种情况下不修改指针?
me
, me1
, and me2
are local variables inside your outer function (let's assume it was main
). me
, me1
和me2
是外部函数内部的局部变量(假设它是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
. 这些指针永远不会被修改,因此在调用test
, me1
仍指向与以前相同的节点,而指针me1->parent->right
现在指向me
。 So, "me1 and me1->parent->right point are the same address" isn't true anymore! 因此,“ me1和me1-> parent-> right point是相同的地址”不再适用!
If you only modify old
inside test
, you will only modify the parameter old
, which is a copy of me1
. 如果仅修改old
内部test
,则将只修改参数old
,它是me1
的副本。 After test
returns, this copy is forgotten, and the modification has no effect. test
返回后,该副本将被遗忘,并且修改无效。 If you want to modify the me1
variable from within test
, you will have to pass a pointer to the pointer, ie a double pointer: 如果要在test
修改me1
变量,则必须将指针传递给该指针,即双指针:
int test(node **old,node* new){
*old = new;
...
}
and call it as test(&me1,me);
并将其称为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
. 另外:请不要将其命名为“ new”,因为如果您决定将代码编译为C ++,则将与保留关键字new
冲突。
Here is what your test()
method does: 这是您的test()
方法的作用:
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: 这些步骤发生:
me1
's parent
is me
and me
's right
is me1
. me1
的parent
是me
和me
的right
是me1
。 So me
's right becomes me
again. 所以me
的权利再次成为me
。 me
's parent
becomes me
itself. me
的parent
就是me
自己。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.