对于你们中的一些人来说,这似乎是一个愚蠢的问题,我知道我经常把事情弄得混乱,但我需要理解代码,这样我就可以停止对它的迷恋,并专注于为什么我需要的真正问题。用它。
所以,在代码中我看到了几个这样的作业:
struct bst_node** node = root;
node = &(*node)->left;
node = &(*node)->right;
is there an invisible parenthesis here?
node = &((*node)->right);
此示例取自literateprograms.org。
所以对我来说似乎&(* node)是不必要的,我不妨只写一个node->左,但代码似乎工作在我无法理解它的地方,我想知道如果是因为我误解了那些线路上发生的事情。特别是,在代码中的一个地方,它通过不断地将“已删除”的数据移动到树的底部来删除节点,以安全地删除节点而不必“破坏”,我迷失了,因为我没有得到如何
old_node = *node;
if ((*node)->left == NULL) {
*node = (*node)->right;
free_node(old_node);
else if ((*node)->right == NULL) {
*node = (*node)->left;
free_node(old_node);
} else {
struct bst_node **pred = &(*node)->left;
while ((*pred)->right != NULL) {
pred = &(*pred)->right;
}
psudo-code: swap values of *pred and *node when the
bottom-right of the left tree of old_node has been found.
recursive call with pred;
}
可以保持树形结构完好无损。我不明白这是如何确保结构完整的,并希望得到一些知道发生了什么的人的帮助。我将节点解释为堆栈上的局部变量,在函数调用时创建。因为它是一个双指针,它指向堆栈中的一个位置(我假设这个,因为它们先前和函数调用的(和*节点)),它自己的堆栈或之前的函数,然后指向堆上的节点。
在上面的示例代码中我认为它应该做的是向左或向右切换,因为其中一个是NULL,然后切换不是的那个(假设另一个不是NULL?)正如我所说,我不确定这是如何工作的。我的问题主要涉及我认为&(* node)< =>节点,但我想知道是不是这种情况等。
答案 0 :(得分:2)
这很有用
&(*node)->left
< => &((*node)->left)
此代码编辑的变量为*node
。我需要这段代码的上下文来提供更多信息
答案 1 :(得分:2)
node = &(*node)->right;
这里有一个不可见的括号吗?
node = &((*node)->right);
是。它取的是right
*node
成员的地址。 ->
优先于&
;请参阅C++ Operator Precedence(->
为2,&
在该列表中为3)(它与C的一般优先级相同)。
所以对我来说似乎&(* node)是不必要的,我不妨只写一个node->左,
你的前提是关闭的。没有表达式&(*node)
,如上所述,&
适用于整个(*node)->left
,而不是(*node)
。
在该代码中,双指针就是指向指针的指针。就像这样:
int x = 0;
int *xptr = &x;
*xptr = 5;
assert(x == 5);
这是相同的,它改变了指针x的值:
int someint;
int *x = &someint;
int **xptr = &x;
*xptr = NULL;
assert(x == NULL);
在您发布的代码段中,分配指向*node
的指针会更改node
指向的指针的值。所以,例如(伪代码):
typedef struct bst_node_ {
struct bst_node_ *left;
struct bst_node_ *right;
} bst_node;
bst_node * construct_node () {
return a pointer to a new bst_node;
}
void create_node (bst_node ** destination_ptr) {
*destination_ptr = construct_node();
}
void somewhere () {
bst_node *n = construct_node();
create_node(&n->left); // after this, n->left points to a new node
create_node(&n->right); // after this, n->right points to a new node
}
由于优先规则,再次注意&n->left
与&(n->left)
相同。我希望有所帮助。
在C ++中,您可以通过引用将参数传递给函数,这与传递指针基本相同,除了语法上它会导致代码更容易阅读。