2017-02-12 154 views
0

我认为我的创作出了问题。如何显示我在链接列表中创建的数据?

void add(N *p) { 
    N *current, *start; 
    current = malloc(sizeof(p)); 
    scanf("%d", &current->data); 
    current->next = NULL; 

    if (p == NULL) { 
     p = current; 
     start = current; 
    } else { 
     start->next = current; 
     start = current; 
    } 
} 

我认为我的display()是正确的。

void display(N *p) { 
    N *current; 
    current = p; 
    while (current != NULL) { 
     printf("\n%d", current->data); 
     current = current->next; 
    } 
} 
+0

你得到了什么错误?什么是期望的输出?你目前的输出是什么? – Yousaf

+0

没有输出...如果我输入1,然后程序停止进程返回0 – Willy

+0

我试过malloc(sizeof(N))。输出是一样的。 – Willy

回答

0

有问题:

  • 功能add()不分配正确的内存量。使用此方法:

    current = malloc(sizeof(*current)); 
    
  • 要插入新分配的对象到列表的方式不起作用:您修改p,这与本地范围的参数,并设置start其中也有本地范围。 N指针是调用者范围,没有副作用。

  • 你的display函数是正确的,但我希望在输出结尾添加新行,而不是在开头。

这里是一个更新的版本具有更好的API:

int add(N **headp) { 
    N *current = calloc(sizeof(*current)); 
    if (current == NULL) { 
     fprintf(stderr, "cannot allocate memory for new object\n"); 
     return -1; 
    } 
    if (scanf("%d", &current->data) != 1) { 
     fprintf(stderr, "cannot read value for new object\n"); 
     return -2; 
    } 
    current->next = *headp; 
    *headp = current; 
    return 0; 
} 

void display(const N *list) { 
    for (const N *p = list; p != NULL; p = p->next) { 
     printf("%d\n", p->data); 
    } 
} 

add功能是由主叫方用这样的方式:

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

typedef struct N { 
    int data; 
    struct N *next; 
} N; 

int main(void) { 
    N *list = NULL; 

    for (i = 0; i < 10; i++) { 
     if (add(&list)) 
      break; 
    } 
    display(list); 
    return 0; 
} 
+0

谢谢。 ... – Willy

+0

我刚刚发现了head = add(head);有用。感谢您的小费。 int main(){ N * head = NULL; head = add(head); display(head); return 0; } – Willy

+0

@Willy:'head = add(head);'不如'add(&head)'强大以提供失败检测。 'add(&head)'可以返回一个表示成功的布尔值或一个表示错误代码的'int'。我更新了代码以反映这种可能性。 – chqrlie

1

malloc(sizeof(p))只返回一个指针足够的空间。你反而想要malloc(sizeof(N))

另外,您需要返回p的新值,而不是在add()的末尾丢弃它。 (您start也有类似的问题,选择一个是你的链表的头。)

+0

好吧。如何在我的显示器?有什么不对? – Willy

+0

@Willy你的'display()'看起来不错。这是你的add()有问题。 – chrisaycock