调用函数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;
}
答案 0 :(得分:1)
initializeLinkedList不会修改main中定义的变量headptr和topptr(按值传递)。因此传递给getLength的变量包含垃圾。
答案 1 :(得分:1)
void initializeLinkedList(node *headptr, node *topptr)
将其更改为
void initializeLinkedList(node *headptr, node** topptr)
并相应地更改您的代码......
还有很多其他问题......
当你需要一个指针时,只需定义指针就不要分配内存并覆盖poiter ..
如果我必须编码
void initializeLinkedList( node **topptr)
{
int i=0;
node* headptr = (node*)malloc(sizeof(node));
headptr->value=i;
*topptr = headptr;
for(i=1;i<5;i++)
{
headptr->nextPtr = (node*)malloc(sizeof(node));
headptr->nextPtr->value=i;
headptr->nextPtr->nextPtr=NULL;
headptr=headptr->nextPtr;
}
}
int main()
{
node* topptr;
initializeLinkedList(&topptr);
printf("val is %d \n", getLength(topptr));
return 0;
}
答案 2 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node *nextPtr;
} node;
void initializeLinkedList(node **top, node **rear){
int i=0;
node *local;
*top = (node*)malloc(sizeof(node));
local = *top;
local->value=i;
local->nextPtr = NULL;
for(i=1;i<5;++i){
local->nextPtr = (node*)malloc(sizeof(node));
local = local->nextPtr;
local->value = i;
local->nextPtr = NULL;
}
*rear = local;
}
int getLength(node *np){
int i;
for(i=0;np!=NULL;++i, np = np->nextPtr)
;//printf("debug:%d\n", np->value);
return i;
}
int main(void){
node *top, *rear;
initializeLinkedList(&top, &rear);
printf("length is %d \n", getLength(top));
return 0;
}