Pegah
Pegah

Reputation: 1

can't use a function with a 'pointer to pointer' input in another function. In C language

this code supposed to print : 'tree two one' but it doesn't work. (the new_nod isn't added to the front of mylist) anybody knows why? (actually in this code i wanted to use a function with a pointer to pointer input in another function but it didn't work(no changes applied to the mylist). but it works when i'm using add_front function straightly in main.

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



struct node{
char *word;
struct node *next;
};


struct node* create_node(char *str){
struct node *s;
s = (struct node *)malloc(sizeof(struct node));
if(s==NULL){
    printf("couldn't malloc :(\n");
    exit(-1);
}

s->word = str;
s->next = NULL;
return s;
}


void print_node(struct node *list){
struct node *current;
for(current = list; current !=NULL; current = current->next)
    printf("%s ", current->word);
}

void add_front(struct node **list, struct node *new_node){
new_node->next= *list;
*list = new_node;}


void func(struct node*list, struct node*new_node){
add_front(&list, new_node);


}



int main()
{
    struct node* mylist = create_node("one");
    mylist->next = create_node("two");

    struct node *new_node = create_node("tree");
    func(mylist, new_node);


print_node(mylist);
}

Upvotes: 0

Views: 34

Answers (1)

Your add_front accepts a pointer to a pointer and other than missing a check for NULL is pretty much okay. But let's take a look at this:

void func(struct node*list, struct node*new_node){
  add_front(&list, new_node);
}

What is add_front modifying here? The local pointer list. Which is just a copy of mylist in main.

So you haven't changed what mylist is pointing to.

Upvotes: 1

Related Questions