0

i have this code to print a linklist [1,2,3]

 void reverse(struct node *ptr){ head = ptr; while(ptr!=NULL){ printf("%d--->",ptr->data); ptr=ptr->next; } } 

output : 1-->2-->3

i am trying to print next element of ptr(current node) like

 void reverse(struct node *ptr){ head = ptr; while(ptr!=NULL){ printf("%d--->",ptr->data); ptr=ptr->next; printf("%d--->",ptr->data); } } 

why is not printing 1-->2-->2-->3-->3 ?

1
  • 1
    In your second code you are doing NULL->data ? Do you understand this? Commented Aug 20, 2013 at 19:18

3 Answers 3

1

You might like to change this

 ptr=ptr->next; printf("%d--->",ptr->data); 

to become

 ptr=ptr->next; if (NULL != ptr) printf("%d--->",ptr->data); 

For the last iteration the program tries to dereference NULL, which leads to undefined behaviour which in turn most propably makes the program crash then.

And as stdout is line buffered the buffer filled with 1-->2-->2-->3 will not be flushed and printed out anymore.


You might have a chance to reproduce this by adding

flush(stdout); 

after each call to print().

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

Comments

1

with the second code you will get a segmentation fault.

Because in this code

ptr=ptr->next; 

where ptr->next is NULL, then ptr will be NULL and then executing

printf("%d--->",ptr->data); 

with ptr = NULL will cause a segmentation fault

1 Comment

Don't directly say segmentation fault better to say Undefined behaviour (may be you get segmentation fault at runtime)
1
void reverse(struct node *ptr){ head = ptr; while(ptr!=NULL){ printf("%d--->",ptr->data); ptr=ptr->next; if (ptr) printf("%d--->",ptr->data); } } 

Try this code. The problem is that ptr will be equal to NULL at a moment during the loop, but you're doing printf("%d--->",ptr->data); just after the assignation of ptr. It's like : printf("%d--->",NULL->data); which leads to an undefined behavior (you will probably get a segmentation fault).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.