【发布时间】:2015-05-23 08:07:13
【问题描述】:
我写了一个函数
void
insertNode(node_t *front, node_t *nodeIn) {
node_t *currentNode = front;
node_t *copy;
if (!(copy = (node_t*)malloc(sizeof(struct node)))) {
printf("Out of memory, exiting here?");
exit(0);
}
strcpy(copy->name, nodeIn->name);
copy->aisle = nodeIn->aisle;
copy->shelf = nodeIn->shelf;
copy->mass = nodeIn->mass;
copy->price = nodeIn->price;
copy->quantity = nodeIn->quantity;
copy->next = NULL;
if (front == NULL || strcmp(front->name,copy->name) > 0) {
copy->next = currentNode;
front = copy;
printf("%s\n", front->name);
}
else {
while (currentNode->next != NULL &&
strcmp((currentNode->next)->name,copy->name) < 0) {
currentNode = currentNode->next;
}
copy->next = currentNode->next;
currentNode->next = copy;
}
}
它接收指向前节点的指针和我想要插入到列表中的节点,但它没有按预期运行。我的代码中有什么明显的地方可能会被破坏吗?
【问题讨论】:
-
front = copy;对调用者传入的front指针执行 nothing。调用者的指针保持不变。这个问题本质上是相同to this question,可以在本页右侧的列表中找到,尽管有比这更好的解决方法。 -
欢迎您。 “它没有按预期运行” 到底是什么意思?您是否收到特定的错误消息或类似的信息?如果是,请将其添加到您的问题中。
-
标签: c memory insert linked-list