2017-01-10 1 views
0

このコードは 'tree two one' を印刷するはずですが動作しません。 (new_nodはmylistの前に追加されていません) なぜ誰が知っていますか? (実際にこのコードでは、別の関数でポインタの入力へのポインタを持つ関数を使用したかったが、動作しなかった(mylistに変更は加えられていない)。 しかし、mainでadd_front関数を使用しているときに機能する。は、別の関数で 'ポインタへのポインタ'入力を持つ関数を使用することはできません。 C言語で

#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); 
} 

答えて

1

あなたadd_frontは、ポインタへのポインタを受け取り、NULLのチェックが欠落以外はかなりいいです。しかし者はこれを見てみましょう:。?add_frontはこちら

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

何を変更していますローカルポインタlist。のmylistのコピーのみです。

したがって、mylistが指しているものは変更していません。

関連する問題