【发布时间】:2020-07-04 06:39:36
【问题描述】:
我在使用和设置链接列表中的指针时遇到了一些麻烦......我的代码中不断出现分段错误,有人在这里看到任何明显的问题吗?
最近,我在编写的每一段代码中都遇到了段错误,这非常令人沮丧,因为我发现它们几乎无法追踪。我是一名物理专业的学生,试图自学如何编码,所以我是一个非常新手程序员,我很抱歉我问了这么一个常见的问题,非常感谢任何建议!
(为了解释代码,我们应该创建一个包含三个随机变量的节点的链表,然后以三种不同的方式对列表进行排序,rand_double 只是生成一个随机双精度并且运行得很好,所以我知道问题是不在那里!!)
Node* randomList(int length){
int i;
Node **head, *new;
head = malloc(sizeof(Node**));
*head = NULL;
new = malloc(sizeof(Node*));
new = NULL;
/*create list by adding new node to beginning of list, using 'push' method*/
for(i=0;i<length; i++){
/*set data in new node*/
new->value = (int)rand_double(0,10);
new->key1 = rand_double(10.0, 50.0);
new->key2 = rand_double(50.0, 90.0);
new->sort1 = malloc(sizeof(Node*));
new->sort2 = malloc(sizeof(Node*));
new->next = malloc(sizeof(Node*));
new->sort1 = NULL;
new->sort2 = NULL;
/*
set pointers
new node points to what head points to, head points to new
*/
new->next = *head;
*head = new;
}
return *head;
}
【问题讨论】:
-
您将 new 分配给 NULL(这是泄漏内存),然后在分配 new->value 时尝试取消引用指针。
-
提示:检查尺寸 -->>
new->sort1 = malloc(sizeof(Node*));
标签: c pointers struct linked-list segmentation-fault