0

I've made a Linked List. Its elements keep both previous and next items' address. It gets commands from an input file. It detects the command and uses the following statement as a parameter. (text: add_to_front john -> means: add_to_front(john))

Code: http://pastebin.com/KcAm1y3L

When I try to give the commands from an input file it gives me same output over and over. However, if I write inputs in main() manually, it works.

For ex input file:

add_to_front john
add_to_back jane
add_to_back jane
print

(unfortunately) the output is:

>add_to_front john
>add_to_back jane
>add_to_back jane
>print
 jane
 jane
 jane

Although, if I write

add_to_front(john);
add_to_back(jane);
add_to_back(jane);
print();

Instead of this command check:

while (scanf("%s",command)!=EOF)
{
    if (strcmp(command,"add_to_front")==0)
    {
        gets(parameter);
        add_to_front(parameter);
    }
    else if (strcmp(command,"add_to_back")==0)
    {
        gets(parameter);
        add_to_back(parameter);
    }
    else if (strcmp(command,"remove_from_back")==0)
        remove_from_back(parameter);
    ...
        printf(" HUH?\n");
    }
}

In main() it gives the correct output.

I know it's a lot to ask but this thing is bothering me for 2 days. What do you think I'm doing wrong?

2
  • 3
    Do not use gets(), even in test code! NEVER use gets()! Commented Jan 16, 2011 at 20:45
  • Debug it (with a debugger...)! Commented Jan 16, 2011 at 20:56

1 Answer 1

2

You don't show the relevant code above. Most likely, you do not copy the data that was read into your list, so you end up storing the last value read over, and over, and over again.


Looking at the code in the paste bin, that is indeed the trouble; you do not copy the strings into your list - you just copy the pointer. You will need to add code to allocate space for the string and copy the string. If it is available to you, the function strdup() does the job neatly. If not, you can easily write your own. Note that this means you will have to free the allocated space too.

Sign up to request clarification or add additional context in comments.

1 Comment

@gcx: even after fixing up the copying of the data, there is some work left to do. The check front/back functions have the same tag, but the check front prints from the back and check back prints from the front. I implemented a plausible looking 'd_free()' but things still get twisted when you do enough adds, frees, and prints. You should look hard at whether baslangic is needed, and why. It might be better to maintain a circular doubly-linked list with a dummy node that is initialized at startup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.