[英]Segmentation fault while getting the size of Linked list
I am getting segmenation fault when calling the function getLength. 调用函数getLength时出现segmenation错误。 I edited the code, now I am getting length as 0 instead of 5.
我编辑了代码,现在我的长度为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;
} }
initializeLinkedList does not modify the variables headptr and topptr defined in main (pass by value). initializeLinkedList不会修改main中定义的变量headptr和topptr(按值传递)。 Hence the variable passed to getLength contains junk.
因此传递给getLength的变量包含垃圾。
void initializeLinkedList(node *headptr, node *topptr)
change it to 改为
void initializeLinkedList(node *headptr, node** topptr)
and change your code accordingly... 并相应地更改您的代码......
There are lot of other issues too... 还有很多其他问题......
When you need a pointer just define the pointer don't allocate memory and overwrite the poiter.. 当你需要一个指针时,只需定义指针就不要分配内存并覆盖poiter ..
If i have to code it 如果我必须编码它
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;
}
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.