【发布时间】:2016-10-19 10:15:30
【问题描述】:
目标:创建单个链表并使用 HEAD POINTER(而不是 HEAD NODE)打印列表。
**start:
是HEAD NODE(FIRST NODE)指针
我不想将 HEAD NODE(FIRST NODE) 存储为
*start,而是将 HEAD NODE 指针存储为**start。
算法:
- 创建包含五个节点的列表(在我的程序中硬编码)。
- 使用指向 HEAD NODE 的指针显示它们
代码中有一个明显的HOLE,不容易出现。 任何人都可以就此提供您的意见。
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *link;
}**start;
void display(void) {
struct node *p;
if (!strart ) { printf("List is empty\n"); return; }
p = *start;
printf("List :");
while(p != NULL) {
printf("-%d", p->data);
p = p->link;
}
puts("");
}
struct node **createlist(void) {
int n;
struct node *p, *new, *tmp;
printf("enter no of elements to add\n");
//scanf("%d", &n);
p = NULL;
n=5;
while(n--) {
new = (struct node *) calloc(1, sizeof(struct node));
new->data = n;
if (p) {
p->link = new;
p = new;
} else if (p == NULL) {
p = tmp = new;
}
}
printf("before assign start :%p\n", start);
start = &tmp;
printf("after assign start :%p\n", start);
printf("In create List :\n");
display();
return start;
}
int main() {
int ch;
do {
printf("1.CreateList 2.DisplayList\n");
//scanf("%d", &ch); //HARDCODED
switch(1) {
printf("switch -> start :%p\n", start);
case 1 : start = createlist();
printf("after create -> start :%p\n", start);
case 2 : printf("Disp:\n"); display(); break;
default : printf("Invalid option\n");
}
} while(0);
return 0;
}
代码输出:
root@CDrive:~/datastructures# ./a.out
1.CreateList 2.DisplayList
enter no of elements to add
before assign start :(nil)
after assign start :0x7ffd13e64798
In create List :
List :-4-3-2-1-0
after create -> start :0x7ffd13e64798
Disp:
Segmentation fault (core dumped)
【问题讨论】:
-
使用
valgrind。 -
使用调试器。
-
struct node **createlist(void)返回一个指向指针的指针在这里没什么意义。
标签: c pointers linked-list