我有一个链表的结构,我想传递一个节点(另一个结构)指针指向一个函数(该节点是链表的一部分,但我将节点单独传递给删除器函数从堆栈内存中删除结构
我希望它复制下一个节点数据到自身(覆盖其数据),并删除下一个节点,从而删除自己(这部分工作)..我做了它检查是否传递的节点是(我知道我可以使用malloc()和free()使用堆内存)。我不知道如何从堆栈中删除结构(我知道我可以malloc()和free()它使用堆内存)。
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int data;
struct node * next;
}node;
typedef struct {
struct node * head;
}linked_list;
void print_list(linked_list * list) {
node *current = list->head;
while (current) {
printf("Current node has %d\n",current->data);
current = current->next;
}
}
void delete_node(node * n) {
node * next = n->next;
if (next) {
n->data = next->data;
n->next = next->next;
}
else {
*n = NULL; /*This of course won't compile because assigning void* (null) to node variable
but if i make n point to NULL, nothing will happen because i'm inside a function
and the pointer is duplicated (the passed pointer will still work) */
}
}
void main(){
node first;
node second;
first.data = 1;
first.next = &second;
second.data = 2;
second.next = NULL;
linked_list l;
l.head = &first;
print_list(&l);
delete_node(&second);
print_list(&l);
}
局部变量不会被删除......您只需终止本地块即可释放该内存。 – mah
但我传递一个函数的指针,我想删除的变量不在该函数的范围内。这是否意味着我根本无法做我想做的事情? – user2263786
您可以从列表中取消链接,但不能删除结构占用的内存。您只能删除首次分配的内容,并且通常以相同的方式删除。由于您的分配是隐式的(通过启动执行块),您的释放也将是隐式的(通过终止执行块)。 – mah