dimanche 8 septembre 2019

Condition if with pointers doesn't work in a loop

I'm trying setting the smaller value, and I'm doing that, it works but I can't compare the last value. when I reach the last value, the segmentation fault appears

int smaller = p->key;
while(p != NULL){
      if(p->next == NULL) break;  //line 2
      if(p->key < smaller) smaller = p->key;
      p = p->next;
}

I think it would be better if I delete line 2, but if I delete, didn't work

//it isn't working
    while(p != NULL){
          if(p->key < smaller) smaller = p->key;
          p = p->next;
   }

//but this works
while(p != NULL){
    printf("%d ", p->key);
    p = p->next;
}

How can I use if(p->key < smaller) smaller = p->key; inside the loop?

Aucun commentaire:

Enregistrer un commentaire