user3150130
user3150130

Reputation: 25

Linked Lists - disappearing data

I need some help with this linked lists exercise. The function listTasks() is supposed to show all the instances of struct task. When I execute the function for the first time, it works as expected, but when I execute it again, it doesn't show the stuff from struct action, even if I execute them one after the other.

typedef struct action
{
    char parametre[100];
    char command[100];
    struct action* next;
    struct action* previous;
}* Action;

typedef struct task
{
    char name[100];
    struct task* next;
    struct task* previous;
    Action action;
}* Task;

void listTasks(Task tar, char* name)
{

    if(tar==NULL) printf("There is no task with the name: %s\n",name);
    else
    {
        while(tar!=NULL&&strcmp(tar->name,name)!=0)
        {
            tar = tar->next;
        }
        if(tar!=NULL && strcmp(tar->name,name)==0)
        {
            printf("Task: %s\n",tar->name);
            if(tar->action==NULL) printf("->It doesnt have any action.\n");
            else if(tar->action!=NULL)
            {
                while(tar->action!=NULL)
                {
                    printf("->Command: %s\n->->Parametre: %s\n",tar->action->command,tar->action->parametre);
                    tar->action = tar->action->next;
                }
            }
        }
        else printf("There is no task with the name: %s\n",name);
    }


}

void main()
{
   task a = NULL;
   listTasks(a,"random name");
}

Upvotes: 0

Views: 168

Answers (1)

Filipe Gonçalves
Filipe Gonçalves

Reputation: 21213

Your problem is here:

while(tar->action!=NULL)
{
    printf("->Command: %s\n->->Parametre: %s\n",tar->action->command,tar->action->parametre);
    tar->action = tar->action->next;
}

You are destructively changing tar->action. Yeah, it works for the first time, but after that, tar->action will be NULL, that's why the data "disappears".

If you don't want to destroy the actions list, you have to traverse it by using a temporary variable. Something along the lines of:

struct action *action = tar->action;
while(action!=NULL)
{
    printf("->Command: %s\n->->Parametre: %s\n",action->command,action->parametre);
    action = action->next;
}

Upvotes: 4

Related Questions