我正在研究一个 LIFO 堆栈结构,以单链表的形式实现:
typedef struct spile {
char ch;
struct spile *address;
} Spile, *Pile;
我想编写一个推送函数,将一个元素(字符)添加到列表的头部。
为什么这样的事情会导致核心转储:
Pile add_head (Pile P, char c) {
P->address = P;
P->ch = c;
return P ;
}
类似的函数(这次删除 head 元素)有效吗?
Pile remove_head (Pile P) {
P = P->adress;
return P;
}
我知道我可以这样处理:
#define MALLOC(t) ((t*)malloc(sizeof(t)))
Pile add_head (Pile P, char c) {
Pile P1 = MALLOC(Spile);
P1->address = P;
P1->ch = c;
return P1;
}
但我希望函数修改 P 并且不返回新指针。此外,由于我没有在任何地方释放(P1),如果我没有弄错的话,上面的版本会导致内存泄漏。
编辑:add_head是这样调用的
Pile my_pile = NULL;
my_pile = add_head(my_pile, 'z');
当我说我想修改 add_head 中的参数 P 时,我的意思是 P 应该由函数返回,但其中包含新元素。
最佳答案
I would like the (
add_head
) function to modify P and not to return a new pointer.
如果要向结构中添加新元素,则需要为该新元素分配内存。
如果这个新元素应该添加到列表的头部,那么头指针将更改到新位置。
Old List with A,B,C
___ ___ ___ ______
| A | --> | B | --> | C | --> | NULL |
|___| |___| |___| |______|
Head
New List after adding element D
___ ___ ___ ___ ______
| D | --> | A | --> | B | --> | C | --> | NULL |
|___| |___| |___| |___| |______|
Head
您编写的第二个函数(使用 malloc
)是必需的。
关于c - 修改并返回指向结构体的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52920433/