How read few times a linked list in while context in C

86 views Asked by At

I try to write a code to read few times a linked list without call a specific function like void print(t_list *list), see the code below. I can figure why my code cannot be read a second time my linked list in the while context, because at the end of my first loop my struct t_list is NULL, and when I start the second while my struct is still NULL and obviously nothing can be used.

So I have two questions,

first : Why I can read twice my linked list when I pass by the function void print(t_list *list), it's good because that's work but I don't understand why in the second read my t_listis not NULL

second : How in the whileor for context, rewind my pointer t_list to the begin, to read again the linked list.

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

typedef struct s_list t_list;
struct s_list {
    int arg;
    t_list *next;
};


int add(t_list **ref, int arg) {
    t_list *temp;
    temp = NULL;
    if(!(temp = (t_list*)malloc(sizeof(t_list))))
        return (0);
    temp->arg = arg;
    temp->next = (*ref);
    (*ref) = temp;
    return(1);
}

void change(t_list *list) {
    printf("change arg:\n");
    while(list) {
        list->arg = 42;
        list = list->next;
    }
}

void print(t_list *list) {
    printf("list:\n");
    while(list) {
        printf("arg: %i\n",list->arg);
        list = list->next;
    }
}

int main() {
    t_list *list;
    list = NULL;
    add(&list, 0);
    add(&list, 1);
    add(&list, 2);
    print(list); // work fine
    change(list);
    print(list); // work fine it's possible te read a second time but why ?
  
    // that's way don't work a second time
    while(list) {
        printf("arg: %i\n",list->arg);
        list = list->next;
    }

    while(list) {
        printf("arg: %i\n",list->arg);
        list = list->next;
    }

    return (0);
}

console

➜  LINKED_LIST git:(master) ✗ clang linked_list.c && ./a.out
print list:
arg: 2
arg: 1
arg: 0
change arg:
print list:
arg: 42
arg: 42
arg: 42
while arg: 42
while arg: 42
while arg: 42
1

There are 1 answers

3
Rohan Kumar On

As pointed out in comments, I think you should read about C Variable Scopes.

When you pass list into print() method value of pointer variable t_list* list gets copied to the argument of print() method. So whatever you do print method's t_list* list doesn't affect main method's t_list* list. You can confirm this by checking value of list before and after calling print() method:

    printf("%p\n", list);
    print(list); 
    printf("%p\n", list);
    print(list); 
    printf("%p\n", list);

They all should print same value since list hasn't been changed in main function's scope:

0x17222e0
list:
arg: 2
arg: 1
arg: 0
0x17222e0
list:
arg: 2
arg: 1
arg: 0
0x17222e0
arg: 2
arg: 1
arg: 0