【发布时间】:2015-06-03 03:06:45
【问题描述】:
我正在做作业,我想我应该使用链表来存储一些数据。问题是列表没有保留所有节点。
当添加完成并尝试查看节点时,它只显示添加到列表中的最后一个节点。
我将在下面写下相关部分,希望有人能指出问题所在。(我怀疑它一定与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);
}
}
【问题讨论】:
-
标准警告:请do not cast
malloc()和C中的家人的返回值。 -
引用支持并提供标准警告的详细说明:c-faq.com/malloc/mallocnocast.html
-
@SouravGhosh 谢谢!
标签: c linked-list malloc