我有以下代码:
#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;
}
它应该打印出来
item1 item2 item3 item4
但它不打印任何东西,我不明白为什么。
答案 0 :(得分: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 :(得分:1)
此方法不会更改root并且也可以正常工作。
#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;
}