我想创建一个将元素添加到链表末尾的函数。如果成功添加了元素,它还必须返回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;
}发布于 2017-10-24 05:35:23
您需要添加以下代码
if (temp1 == NULL) { return 1; }因为malloc被定义为返回一个指向已分配内存的指针,或者
您可以控制不请求大小为零,因此如果您使用了正的大小,并且malloc返回NULL,则可以推断发生了错误。
许多系统都安装了“手册”。如果您使用的是Linux系统,命令"man malloc“将弹出malloc的手册页。如果你在Windows系统上工作,在网络上搜索the manual for malloc会给你足够的细节来处理细节。
发布于 2017-10-24 05:50:02
该函数有一个缺点:它不能用于分配列表中的第一个节点,即如果列表为空。
原型应更改为
int push_back(pos_t **headp, int new_value);传递列表指针的地址而不是它的值。
测试malloc()失败很简单: juts将返回的指针与NULL或0进行比较。
下面是相应的代码:
int push_back(pos_t **headp, int new_value) {
pos_t *temp = *headp;
pos_t *temp1 = malloc(sizeof(pos_t));
if (temp1 == NULL) { // allocation failure
return 1;
}
temp1->data = new_value;
temp1->next = NULL;
if (temp == NULL) { // empty list
*headp = temp1;
} else {
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = temp1; // append node to the end of the list
}
return 0;
}https://stackoverflow.com/questions/46898600
复制相似问题