我正在做作业,我想我应该使用链表来存储一些数据。问题是列表没有保留所有节点。
添加完成后我尝试查看节点,它只显示添加到列表中的最后一个节点。
我将在下面写相关部分,我希望有人可以指出问题是什么。(我怀疑它必须是与malloc相关的东西。地址在函数完成其工作后被销毁,但我不确定。
另外我应该指出,我测试过,在添加数据时打印数据,并且确实显示它们已正确添加到列表中。)
/**
* Adds command name and it's hash onto the linked list
* returns 1, if successful
* returns 0, if failed
*/
int addToList(struct CMDList *head, char *pathCommand[], char *hash){
int result = 0;
/** If head was pointing to NULL, list empty, add at the beginning */
if(head->path == NULL){
head->path = pathCommand[0];
head->command = pathCommand[1];
head->hash = hash;
head->next = NULL;
result = 1;
}else{
struct CMDList *current = head;
/** Find tail of the list */
while(current->next != NULL){
current = current->next;
}
current->next = (struct CMDList *)malloc(sizeof(struct CMDList));
if(current->next != NULL){
current->path = pathCommand[0];
current->command = pathCommand[1];
current->hash = hash;
current->next = NULL;
result = 1;
}
}
return result;
}
主程序:
int main(int argc, char *argv[]){
/** CODE DELETED */
/** initialize list for storing cmds from config file */
/** cmdList is the head node that i use to traverse the list */
cmdList = (struct CMDList *)malloc(sizeof(struct CMDList));
if(cmdList != NULL){
cmdList->path = NULL;
cmdList->command = NULL;
cmdList->hash = NULL;
cmdList->next = NULL;
}else{
printError("Silent Exit: couldn't initialize list to store commands of config file");
exit(1);
}
/** CODE DELETED **/
/** add new data to the list */
if(!addToList(cmdList,arrayCommand,sha)){
printError("Silent Exit: couldn't add to list");
exit(1);
}
}
答案 0 :(得分:4)
在这部分代码中:
if(current->next != NULL){
current->path = pathCommand[0];
current->command = pathCommand[1];
current->hash = hash;
current->next = NULL;
result = 1;
}
您必须使用current->next->...
而不是current->...
,因为您的新元素位于current->next
,而不是current
(事实上,您检查了current->next != NULL
})。
由于此错误,添加的第一个元素很好,但是当您尝试添加第二个元素时,只需分配其空间,然后覆盖第一个。
答案 1 :(得分:1)
在这部分代码中,您要设置变量 对于当前 - >下一个
if(current->next != NULL){
current->path = pathCommand[0];
current->command = pathCommand[1];
current->hash = hash;
current->next = NULL;
result = 1;
}
另一个选择是,在执行malloc时,设置一个指向新结构的临时指针,
提供您需要的值,然后设置current->next = temp;
您也可以跳过while步骤。你可以有一个名为tail的指针 指向列表的末尾。
做一些像
这样的事情temp=malloc(...)
temp->path = ...
...
tail->next = temp;
tail = temp;