调用函数 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;
}