2013-06-19 53 views
0

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

}

+2

计数在列表中的元素时,你为什么要分配的东西?你只需要迭代列表并增加一个计数器。 – Max

+2

我其实并没有看到上面提到的问题,只是一个声明和一些代码。 –

+0

我同意Max,我编辑了代码,仍然没有得到正确的结果。 – user968000

回答

1
void initializeLinkedList(node *headptr, node *topptr) 

将其更改为

void initializeLinkedList(node *headptr, node** topptr) 

,并相应地改变你的代码...

有很多太等问题...

当你需要一个指针只是定义指针不分配内存并覆盖主角。

如果我必须对它进行编码

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; 
    } 
1

initializeLinkedList不修改变量headptr和在主定义topptr(按值传递)。因此传递给getLength的变量包含垃圾。

+0

编辑之后,'headptr'和'topptr'是文件范围对象,所以它不再是垃圾,而是它们是'NULL'。但诊断保持不变。 –

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; 
}