【发布时间】:2021-02-21 18:22:28
【问题描述】:
在课堂上我学会了不要返回指向局部变量的指针。在我发现的这个函数中,排序合并,它似乎返回了一个指向节点的指针。怎么会这样?
struct node *SortedMerge(struct node *a, struct node *b) {
struct node dummy; // a dummy first node to hang the result on
struct node *tail = &dummy; // Points to the last result node --
// so tail->next is the place to add
// new nodes to the result.
dummy.next = NULL;
while (1) {
if (a == NULL) { // if either list runs out, use the other list
tail->next = b;
break;
} else
if (b == NULL) {
tail->next = a;
break;
}
if (a->data <= b->data) {
MoveNode(&(tail->next), &a);
} else {
MoveNode(&(tail->next), &b);
}
tail = tail->next;
} //end while
return (dummy.next);
}
void MoveNode(struct node **destRef, struct node **sourceRef) {
struct node *newNode = *sourceRef; // the front source node
assert(newNode != NULL);
*sourceRef = newNode->next; // Advance the source pointer
newNode->next = *destRef; // Link the old dest off the new node
*destRef = newNode; // Move dest to point to the new node
}
【问题讨论】:
-
它没有返回指向局部变量的指针。它返回
dummy.next,这是一个来自调用者的指针。 -
dummy.next是否曾经指向局部变量?在我看来它不像。 -
@Kevin 不是在函数中创建了 dummy ,这意味着它是本地的吗?
-
dummy是本地的,如果您返回&dummy,那将是一个问题。但是dummy.next是一个不指向局部变量的指针,所以可以作为返回值使用。 -
@RoshanSamarawickrema 当您返回指向局部变量的指针时,问题就来了。指针本身是本地的不是问题。
标签: c algorithm merge linked-list mergesort