【发布时间】:2014-05-29 19:02:16
【问题描述】:
我正在用 C 语言编写一个带有插入和打印功能的链表。但是,我从插入中得到了一个分段错误,当我尝试解决这个问题时,我最终得到了一个来自打印功能的错误。任何帮助将不胜感激。
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;
}
【问题讨论】:
-
为什么在 malloc 之后立即将 list 设置为 NULL?
-
这个问题似乎离题了,因为它是关于另一个在调试时没有尝试过的链接列表。
-
我同意@Martin。出于这个原因,我给出了修复的建议,而不是确切的代码修复。
标签: c list pointers linked-list computer-science