Я выполняю задание, и я думал, что должен использовать связанный список для хранения некоторых данных. Проблема в том, что список не сохраняет все узлы.Выполнение связанного списка C
При добавлении финиша, и я пытаюсь увидеть узлы, он показывает только последний узел, который был добавлен в список.
Я напишу соответствующую часть ниже, я надеюсь, что кто-то может указать, в чем проблема. (Я подозреваю, что это должно быть что-то связанное с 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);
}
}
Standard Предупреждение: [не отбрасывают] (http://stackoverflow.com/q/605845/2173917) возвращаемое значение 'таНос()' и семьи в 'C'. –
Цитата, поддерживающая и обеспечивающая разработку стандартного предупреждения: http://c-faq.com/malloc/mallocnocast.html – Sebivor
@SouravGhosh благодарит! – Neo