当临时堆栈分配指针用作 return 值时会发生什么情况?
What happens to a temporary stack allocated pointer when used as a return value?
我正在做一些基本的 leetcode 问题。在这里,我尝试使用递归交换成对的单向链表。下面的代码通过了测试,但有一点我没有理解。 new_head
是在堆栈上创建的指针。我理解这意味着一旦函数 returns 它被清理并且可能指向垃圾。假设它在这里“偶然”起作用并且不是正确的方法是正确的还是我的理解错误?
/**
* 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;
}
另一个与上述代码相关的问题:
如果我改变分配的顺序,我会得到堆栈溢出,但我无法理解为什么
new_head = head->next;
new_head->next = head;
head->next = swapPairs(head->next->next);
这一行 new_head->next = head;
中没有任何内容对递归内部发生的事情有影响 否(它肯定有,但我错过了)?
第一个问题
Return return new_head;
不会 return 对象 new_head
给调用者。它 return 是 new_head
给调用者的当前值。没关系。
第二个问题
有:
new_head = head->next;
head->next = swapPairs(head->next->next);
new_head->next = head;
在调用swapPairs
时,传递给它的值head->next->next
是列表中超出head->next
的某个节点的地址。
有:
new_head = head->next;
new_head->next = head;
head->next = swapPairs(head->next->next);
在调用swapPairs
时,传递给它的值head->next->next
是head
,因为new_head->next = head;
只是将head->next->next
设置为head
.
我正在做一些基本的 leetcode 问题。在这里,我尝试使用递归交换成对的单向链表。下面的代码通过了测试,但有一点我没有理解。 new_head
是在堆栈上创建的指针。我理解这意味着一旦函数 returns 它被清理并且可能指向垃圾。假设它在这里“偶然”起作用并且不是正确的方法是正确的还是我的理解错误?
/**
* 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;
}
另一个与上述代码相关的问题:
如果我改变分配的顺序,我会得到堆栈溢出,但我无法理解为什么
new_head = head->next;
new_head->next = head;
head->next = swapPairs(head->next->next);
这一行 new_head->next = head;
中没有任何内容对递归内部发生的事情有影响 否(它肯定有,但我错过了)?
第一个问题
Return return new_head;
不会 return 对象 new_head
给调用者。它 return 是 new_head
给调用者的当前值。没关系。
第二个问题
有:
new_head = head->next;
head->next = swapPairs(head->next->next);
new_head->next = head;
在调用swapPairs
时,传递给它的值head->next->next
是列表中超出head->next
的某个节点的地址。
有:
new_head = head->next;
new_head->next = head;
head->next = swapPairs(head->next->next);
在调用swapPairs
时,传递给它的值head->next->next
是head
,因为new_head->next = head;
只是将head->next->next
设置为head
.