1

Can't seem to work out why I'm getting garbage output from this Linked List structure when I print the contents.

My goal is to add anything to the list, some string, char by char, an it should print it out in reverse. The reason Im using the extra Struct for Head + Tail is so that I can then print out the the order lines were entered in reverse as well.

typedef struct List {
 char c;
 struct List *next;
}List;

typedef struct  {
 List *head;
 List *tail;
}FullList;

List* InsertList(int hd, List* t1) {
 List *t = (List*)calloc(1,sizeof(List));
 t->c = hd; 
 t->next = t1;
return t;
}


FullList addToStart(FullList c, char element) {
 if (c.head == NULL) {
    c.head = c.tail = InsertList(element, NULL);
 }else {
    c.head = InsertList(element, c.head);
 }
return c;
}

int main(void) {
 FullList InOrder;
 FullList Reverse;
 InOrder.head = NULL;
 Reverse.head = NULL;
 char c;

  while ((c = getchar() != '.')) {
    InOrder = addToStart(InOrder, c);
 }
  while (InOrder.head->next != NULL) {
    printf("%c", (InOrder.head->c));
    InOrder.head = InOrder.head->next;

}     
return 0;           
}

1 Answer 1

5

The problem is here:

while ((c = getchar() != '.')) 

it should be:

while ((c = getchar()) != '.') 

because != has higher precedence than =.

What you are doing in while ((c = getchar() != '.')) is:

  1. You read a character by calling getchar.
  2. Compare if the character read is period or not.
  3. Assign the result of comparison to c, so your c will be either 0 or 1. And when you print the character with value 1 you see that weird looking char.

Also note that the return type of getchar is int, so you need to declare c as int.

Also

while (InOrder.head->next != NULL) 

should be:

while (InOrder.head != NULL)

else you prematurely terminate the loop without processing the last node.

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

5 Comments

Cheers, although it seems to skip off the first letter of what I input for example: Hello, prints olle but no H.
Still cant seem to get that last char printing for some reason, it just skips it entirely.
@user1048116 change while (InOrder.head->next != NULL) to while (InOrder.head != NULL)
Fixed :) Cheers for all the help!
hehe Seth, liturally fixed that as you posted that!

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.