我正在使用插入和打印功能处理C中的链接列表。但是,我从插入中得到了一个分段错误,当我尝试修复它时,我最终得到了一个来自print函数的错误。任何帮助将不胜感激。
typedef struct node
{
struct node *next;
double value;
} NodeT, *NodeTP;
int listSize = 0;
int insert(NodeT *firstEle, int value)
{
NodeTP temp;
if((temp = (NodeTP)malloc(sizeof(NodeT))) == NULL)
{
return 0;
}
// first node in the list.
if(listSize == 0)
{
firstEle->value = value;
firstEle->next = NULL;
}
// finds the end node and adds the new node to the list.
else
{
while(temp != NULL)
{
temp = temp->next;
}
temp->value = value;
temp->next = firstEle;
firstEle = temp;
}
listSize++;
return 1;
}
int print(NodeT List)
{
printf("Element: %.2f\n", List.value);
return 1;
}
int main(int argc, char* argv[])
{
// creates the list.
NodeTP list;
if((list = (NodeTP)malloc(sizeof(NodeT))) == NULL)
{
return 0;
}
list = NULL;
insert(list, 5);
print(list[0]);
insert(list, 15);
print(list[1]);
return EXIT_SUCCESS;
}
答案 0 :(得分:2)
打印问题
对于print语句,您使用的语法无效。您创建了一个单指针,并为该指针及其指向的内容分配了足够的内存。您没有创建NodeT元素数组。因此,list[x]
将无效。
您需要生成一个能找到' x'您正在制作的列表中的元素。您可以在您编写的print
函数中包含它。只需将其更改为获取所需元素的int:
int print(NodeT head, int element) {}
如果要求的元素超出当前范围,请不要忘记检查边界。
您真正需要做的就是逐步完成所需的元素。
插入问题
在你的if / else语句中,为什么要尝试迭代' temp'? '温度'是在此函数中创建的,不应该附加其他元素。你应该重复一遍' firstEle'。您也不想设置firstEle = temp;
,因为它会覆盖以前的内容,而您现在指的是其他内容。
简化此代码的一种方法是使用头部和尾部。头部永远不会改变,但尾部随着元素的增加而移动。你可以插入'返回尾部,当你插入一个新元素时,只需提供尾部,新元素将被添加到那里,不需要迭代。
内存问题
虽然这对于这个程序来说不是主要的,但我会调整我的新节点malloc,直到我确保它不是第一个元素。否则,您将分配一个从未使用过的块。或者,如果这是要添加的第一个元素,请释放该块。
弗雷德提出了一个很好的观点。这将导致问题。
答案 1 :(得分:0)
多个问题(清单远未完成):
malloc()
和printf()
的包含文件。main()
中分配内存,但不要使用它。insert()
中的列表头,则必须将指针传递给它。insert()
中的内存分配是否成功,但是没有处理它没有的情况 - 所以你也可以摆脱它。insert()
和print()
的返回值时,您也可以将其返回类型更改为void
。temp
)覆盖到刚刚分配的内存中。这是一个版本,我至少修复了最基本的错误,以使其编译并至少工作。它仍然远非完美(甚至可以接受),但我尝试尽可能少地改变,以便更容易发现差异并了解你做错了什么,并从那里进一步改进。
#include <stdlib.h>
#include <stdio.h>
typedef struct node
{
struct node *next;
double value;
} NodeT, *NodeTP;
int listSize = 0;
int insert(NodeT **firstEle, int value)
{
NodeTP temp, lastEle;
temp = (NodeTP)malloc(sizeof(NodeT));
// first node in the list.
if(listSize == 0)
{
temp->value = value;
temp->next = NULL;
*firstEle = temp;
}
// finds the end node and adds the new node to the list.
else
{
for (lastEle = *firstEle;lastEle->next != NULL;lastEle = lastEle->next);
temp->value = value;
temp->next = NULL;
lastEle->next = temp;
}
listSize++;
return 1;
}
int print(NodeT List)
{
printf("Element: %.2f\n", List.value);
return 1;
}
int main(int argc, char* argv[])
{
// creates the list.
NodeTP list;
list = NULL;
insert(&list, 5);
print(*list);
insert(&list, 15);
print(*list->next);
return EXIT_SUCCESS;
}