-4

a:

while(temp->data<data)
{
     k=temp;
     temp=temp->next;
     if(temp==NULL)
     break;
}

b:

while(temp->data<data&&temp!=NULL)
 {
     k=temp;
     temp=temp->next;
 }

Question:

I cant find any difference between above two while loops but getting correct answer only by a) and segmentation fault by b)

Duck Dodgers
  • 3,409
  • 8
  • 29
  • 43
  • 1
    This is where a debugger comes in handy... It'll tell you exactly where you got your seg fault, and allow you to look at the variables to work out why. Asking people online might help you THIS time, but learning to use the debugger is a skill you'll need if you plan to write any program. – UKMonkey Dec 27 '18 at 15:15
  • Hint: [short circuit evaluation](https://en.m.wikipedia.org/wiki/Short-circuit_evaluation). – Jesper Juhl Dec 27 '18 at 15:30
  • Possible duplicate: https://stackoverflow.com/questions/628526/is-short-circuiting-logical-operators-mandated-and-evaluation-order – Jesper Juhl Dec 27 '18 at 15:31
  • BTW, you are allowed to add spaces to a program. They make the program easier to read and have no effect on the efficiency of the program. I recommend spaces around operators, such as `<` and `&&`. – Thomas Matthews Dec 27 '18 at 18:13
  • This is a perfectly reasonable question, there is no need to thumb it down just because the person asking does not know the answer. The question is clear and the answer is educational. The comments here are laughable. A debugger would not easily show you as the problematic issue is in a single statement; the possible duplicate is general and high level, and space make no difference here. – Dino Dini Mar 31 '19 at 01:26

2 Answers2

1

Hey the problem in the second one is that you try to access temp->data even when temp is NULL.

A solution would be:

while(temp!=NULL&&temp->data<data)
{
    k=temp;
    temp=temp->next;
}

You need to read the statement from left to right: First see if temp is not null then check for its data

0

I would try swapping

temp->data<data&&temp!=NULL

with

temp!=NULL&&temp->data<data

and read up on the way the && operator works... you want to check for NULL before you access the contents of temp.

Dino Dini
  • 433
  • 3
  • 6