【发布时间】:2018-04-04 13:07:48
【问题描述】:
我想创建一个将元素添加到链表末尾的函数。如果元素添加成功,它还必须返回 0,如果无法为元素分配/保存内存,则返回 1。
问题是,如何知道内存分配成功还是元素添加成功?这是代码:
int push_back(pos_t *head, int new_value) {
pos_t *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
pos_t *temp1 = (pos_t *)malloc(sizeof(pos_t));
temp1->data = new_value;
temp1->next = NULL;
temp = temp1;
}
【问题讨论】:
-
temp=temp1;-->temp->next = temp1;? -
head == NULL可能吗?看看链接列表是如何初始化的会很有用。
标签: c memory linked-list malloc