C - 通过引用调用
我编写了一个简单的程序,对数字的重复时间进行一一排序,然后将它们一一插入到树中。我的问题是,我无法插入 root 的子级,因为我无法将下面的函数更改为按引用调用类型。
我认为下面的 q 参数需要保存根的地址值。
void insertNode(int data, node *q, node *parent){
if(q == NULL){
node *p = createNode(data);
p -> parent = parent;
p -> key = generateKey(p);
int i;
for(i = 0;table[i][1] != 0;i++);
table[i][1] = p -> data;
table[i][0] = p -> key;
q = p;
}
else if(q -> left > q -> right || q -> left == q -> right){
q -> right++;
insertNode(data, q -> rightChild, q);
}
else if(q -> right > q -> left){
q -> left++;
insertNode(data, q -> leftChild, q);
}
}
i wrote a simple program to sort numbers one by one for their repeat time and then inserts them one by one to tree. My problem is, i couldn't insert root's children because i couldn't change the function below to call-by-reference type.
q parameter below needs to hold the root's address value i think.
void insertNode(int data, node *q, node *parent){
if(q == NULL){
node *p = createNode(data);
p -> parent = parent;
p -> key = generateKey(p);
int i;
for(i = 0;table[i][1] != 0;i++);
table[i][1] = p -> data;
table[i][0] = p -> key;
q = p;
}
else if(q -> left > q -> right || q -> left == q -> right){
q -> right++;
insertNode(data, q -> rightChild, q);
}
else if(q -> right > q -> left){
q -> left++;
insertNode(data, q -> leftChild, q);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C 中不存在“按引用传递”之类的东西。如果您需要为传递到函数中的指针分配一个新值(不仅仅是更改指针指向的内容),您将需要将指针传递给指针,即,
当您在 C 中传递指针(或其他任何内容)时,您正在传递指针的副本。因此,这种类型的更改对于函数的调用者是可见的:
但这并不是因为您只是修改传递给函数的副本:
您需要添加另一个间接级别以修改参数本身,以便更改在函数外部可见。
There is no such thing as "pass by reference" in C. If you need to assign a new value to the pointer passed into the function (not merely changing what the pointer points to) you will need to pass a pointer to the pointer, i.e.,
When you pass a pointer (or anything else) in C you are passing a copy of the pointer. So, this type of change is visible to callers of your function:
but this is not because you are only modifying the copy passed to the function:
You need to add another level of indirection in order to modify the argument itself such that the change is visible outside of the function.
“if(q == NULL){ 中分配的节点
}" 块丢失;一旦函数返回,调用者就没有可用的指向它的指针。(q=p;赋值不执行任何操作)
更新:**p 也使您能够删除递归:
The node allocated in the "if(q == NULL){
}" block is lost; once the function returns, there is no pointer to it available to the caller. (the q=p; assignment does nothing)
UPDATE: the **p enables you to remove the recursion as well:
这个怎么样?
How about this?