2017-04-27 195 views
1

我有以下代码:C字符串和指针

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
struct wordlist { 
    char *value; 
    struct wordlist *next; 
}; 
int compare (struct wordlist *one , struct wordlist *two) { 
    return strcmp(one->value, two->value); 
} 
void add(struct wordlist *pp, char *value) { 
    struct wordlist *new; 
    new = malloc(sizeof(*new)); 
    new->value = value; 
    for (; pp != NULL; pp = pp->next) { 
     if (compare(pp, new) > 0) { 
      break; 
     } 
    } 
    new->next = pp; 
    pp = new; 
} 
void display(struct wordlist *ptr) { 
    for (; ptr != NULL; ptr = ptr->next) { 
     printf("%s\n", ptr->value); 
    } 
} 

打破它在中间才能提交。对不起

int main(void) { 
    struct wordlist *root = NULL; 
    add(root, "item1"); 
    add(root, "item2"); 
    add(root, "item4"); 
    add(root, "item3"); 
    display(root); 
    return 0; 
} 

应该打印出来

物品1 ITEM2项目3 ITEM4

但它不打印任何东西,我不明白为什么。

+0

是啊,我也是,,,,,为什么不能'改变(5);'不会改变'5' ..:d –

+0

笑,我理解的代码,但我不能看到任何理由它不会工作 – Yonlif

+0

哪条线? @TonyTannous – Yonlif

回答

1

是否需要将指针传递给指针?

void add(struct wordlist **pp, char *value) { 
struct wordlist *new; 
new = malloc(sizeof(*new)); 
new->value = value; 
for (; (*pp) != NULL; (*pp) = (*pp)->next) { 
    if (compare((*pp), new) > 0) { 
     break; 
    } 
} 
new->next = (*pp); 
(*pp) = new; 
} 
+1

您应该在for-loop中使用其他变量 – BLUEPIXY

+1

另外插入位置之前的列表丢失。 – BLUEPIXY

+0

* OP中的所有*'pp'应该在您的建议中变成'(* pp)'。 – alk

1

此方法不改变根目录,也工作。

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
struct wordlist { 
    char *value; 
    struct wordlist *next; 
}; 

int compare (struct wordlist *one , struct wordlist *two) { 
    return strcmp(one->value, two->value); 
} 

void add(struct wordlist *pp, char *value) { 
    struct wordlist *new; 

    new = malloc(sizeof(*new)); 
    new->value = value; 

    for (; pp->next != NULL; pp = pp->next) { 
     if (compare(pp->next, new) > 0) { 
      break; 
     } 
    } 
    new->next = pp->next; 
    pp->next = new; 

} 
void display(struct wordlist *ptr) { 
    while (ptr->next != NULL) { 
     ptr = ptr->next; 
     printf("%s\n", ptr->value); 
    } 
} 

int main(void) { 
    struct wordlist root; 

    root.next = NULL; 
    add(&root, "item1"); 
    add(&root, "item2"); 
    add(&root, "item4"); 
    add(&root, "item3"); 
    display(&root); 
    return 0; 
} 
+0

它的剂量,但我不想一直改变根。不管怎么说,还是要谢谢你 – Yonlif