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_list
is not NULL
second : How in the while
or 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
As pointed out in comments, I think you should read about C Variable Scopes.
When you pass
list
intoprint()
method value of pointer variablet_list* list
gets copied to the argument ofprint()
method. So whatever you doprint
method'st_list* list
doesn't affect main method'st_list* list
. You can confirm this by checking value oflist
before and after callingprint()
method:They all should print same value since
list
hasn't been changed in main function's scope: