Home > Enterprise >  variable "tmp" used in loop condition not modified in loop body
variable "tmp" used in loop condition not modified in loop body

Time:10-28

#include <stdio.h>
#include <stdlib.h>

 typedef struct node{
     int number;
     struct node* next;
}
node;
int main(void){
    node* list = NULL;
    node *n = malloc(sizeof(node));
    if(n==NULL){
     return 1;
    }
    n->number = 2;
    n-> next = NULL;
    list = n;

    n = malloc(sizeof(node));
    if(n == NULL){
     free(list);
     return 1;
    }
     n->number = 3;
     n->next = NULL;
     list->next = n;

     n = malloc(sizeof(node));
     if(n == NULL){
     free(list->next);
     free(list);
     }
     n->number = 4;
     n->next = NULL;
     list->next->next =n;

     n = malloc(sizeof(node));
     if(n!=NULL){
          n->number = 0;
          n->next = NULL;
          n->next = list;
          list = n;
     }

     for( node* tmp = list; tmp != NULL; tmp->next){
          printf("%i\n" , tmp->number);
     }
     while(list!=NULL){
          node*tmp = list->next;
          free(list);
          list=tmp;
     }
     }

was trying linked list. expected when running the code: 0 1 2 3 4 $ //asdoihasidashiofdhiohdfgdiwheifiopioioiophfaifjasklfhafiashfauiosfhwuiohwefuiowhfaslfidasdaskdasjdlaksdjqwfiqpweiojfkldfjsdfklwhefiowefweopfiosfkosid;fjwdfp;fdasiopfjew[0fowejfwepfojmofejmiwrfgj;wdfjewio;fijwefjsdp;jfkl;wjw

CodePudding user response:

Actually you are not changing the pointer

for( node* tmp = list; tmp != NULL; tmp->next){

You need to write

for( node* tmp = list; tmp != NULL; tmp = tmp->next){

It even be better to write

for ( const node* tmp = list; tmp != NULL; tmp = tmp->next ){

Also in this code snippet

 if(n!=NULL){
      n->number = 0;
      n->next = NULL;
      n->next = list;
      list = n;
 }

the statement

      n->next = NULL;

is redundant.

CodePudding user response:

In this loop, tmp->next has no effect because you don't assign it to anything.

for (node* tmp = list; tmp != NULL; tmp->next) {
    printf("%i\n", tmp->number);
}

You must do tmp = tmp->next:

for (node* tmp = list; tmp != NULL; tmp = tmp->next) {
//                                  ^^^^^
    printf("%i\n", tmp->number);
}

Also, you can't expect 1 to be in the output because you never create a node with that number. With the above change the program will therefore output:

0
2
3
4
  • Related