[英]What happens to a temporary stack allocated pointer when used as a return value?
I'm doing some basic leetcode questions.我正在做一些基本的 leetcode 问题。 Here I'm trying to swap pairs of a singly-linked list using recursion.在这里,我尝试使用递归交换成对的单链表。 The code below passes the tests but some point eludes me.下面的代码通过了测试,但有些地方让我无法理解。 new_head
is a pointer created on the stack. new_head
是在堆栈上创建的指针。 I understand it means that once the function returns it is cleaned up and can potentially point to garbage.我理解这意味着一旦 function 返回它就会被清理并可能指向垃圾。 Is it correct to assume that here it works "by accident" and is not correct way to do it or is my understanding wrong?假设它在这里“偶然”起作用并且不是正确的方法是正确的,还是我的理解错误?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head){
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode* new_head;
new_head = head->next;
head->next = swapPairs(head->next->next);
new_head->next = head;
return new_head;
}
Another question related to the code above:与上述代码相关的另一个问题:
if I change the order of assignments I get a stack overflow but I can't wrap my head around the reason why如果我更改分配的顺序,我会得到堆栈溢出,但我无法理解为什么
new_head = head->next;
new_head->next = head;
head->next = swapPairs(head->next->next);
Nothing that is touched in this line new_head->next = head;
此行中没有任何内容new_head->next = head;
has an effect on what happens inside the recursion no (well it must have but I missing it)?对递归内部发生的事情有影响吗(它必须有,但我错过了)?
Return return new_head;
return return new_head;
does not return the object new_head
to the caller.不会将 object new_head
返回给调用者。 It returns the current value of new_head
to the caller.它将new_head
的当前值返回给调用者。 That is fine.那也行。
With:和:
new_head = head->next;
head->next = swapPairs(head->next->next);
new_head->next = head;
at the time swapPairs
is called, the value passed to it, head->next->next
, is the address of some node beyond head->next
in the list.在调用swapPairs
时,传递给它的值head->next->next
是列表中超出head->next
的某个节点的地址。
With:和:
new_head = head->next;
new_head->next = head;
head->next = swapPairs(head->next->next);
at the time swapPairs
is called, the value passed to it, head->next->next
, is head
, because new_head->next = head;
在调用swapPairs
时,传递给它的值head->next->next
是head
,因为new_head->next = head;
just set head->next->next
to head
.只需将head->next->next
设置为head
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.