如何显示我在链接列表中创建的数据?
我认为我的创作出了问题。如何显示我在链接列表中创建的数据?
void add(N *p) {
N *current, *start;
current = malloc(sizeof(p));
scanf("%d", ¤t->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;
}
}
有问题:
-
功能
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", ¤t->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;
}
你malloc(sizeof(p))
只返回一个指针足够的空间。你反而想要malloc(sizeof(N))
。
另外,您需要返回p
的新值,而不是在add()
的末尾丢弃它。 (您start
也有类似的问题,选择一个是你的链表的头。)
好吧。如何在我的显示器?有什么不对? – Willy
@Willy你的'display()'看起来不错。这是你的add()有问题。 – chrisaycock
你得到了什么错误?什么是期望的输出?你目前的输出是什么? – Yousaf
没有输出...如果我输入1,然后程序停止进程返回0 – Willy
我试过malloc(sizeof(N))。输出是一样的。 – Willy