当我在链表中定义一个节点时,我遇到了这种困惑。 考虑一下,
struct node *current = head;
这里head
是指向头节点的指针。另一种方法是,
struct node *current = (struct node*)malloc(Sizeof(struct node));
current = head;
两者的工作原理相同,那么它们之间有什么区别? 第一种情况如何分配内存?
最佳答案
不同之处在于第二个版本调用了malloc(sizeof(struct node))
并丢失了返回的指针;即这是内存泄漏。您可以通过执行以下操作获得相同的效果:
malloc(sizeof(struct node));
struct node *current = head;
关于c - c中的结构内存分配和malloc(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46269354/