调用函数getLength时出现分段错误。我编辑的代码,现在 我得到长度0代替5.获取链接列表大小时出现分段错误
#include <stdio.h>
#include <stdlib.h>
node *headptr;
node *topptr;
typedef struct node
{
int value;
struct node *nextPtr;
}node;
void initializeLinkedList(node *headptr, node *topptr)
{
int i=0;
headptr = (node*)malloc(sizeof(node));
topptr = (node*)malloc(sizeof(node));
topptr = headptr;
headptr->value=i;
headptr->nextPtr = (node*)malloc(sizeof(node));
for(i=1;i<5;i++)
{
headptr = headptr->nextPtr ;
headptr->value=i;
headptr->nextPtr=(node*)malloc(sizeof(node));
printf("val is %p \n ", *headptr);
}
headptr->nextPtr = NULL;
}
int getLength(node *topptr)
{
int i=0;
node* local;
local = topptr;
while(local!=NULL)
{
local=local->nextPtr;
i++;
}
return i;
}
int main()
{
initializeLinkedList(headptr,topptr);
printf("val is %d \n", getLength(topptr));
return 0;
}
计数在列表中的元素时,你为什么要分配的东西?你只需要迭代列表并增加一个计数器。 – Max
我其实并没有看到上面提到的问题,只是一个声明和一些代码。 –
我同意Max,我编辑了代码,仍然没有得到正确的结果。 – user968000