[英]unknown value linked list in C
my program supposed to print 我的程序应该打印
9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
but it print 但它打印
9 8 7 6 5 4 3 2 1 0 245858 558254 9 8 7 6 5 4 3 2 1 0 245858 558254
and i cant find the problem 我找不到问题
create_list is a fucnction that return a pointer to a list_value "linked list" create_list t calls for insertion function to add a new value in the head of the linked list. create_list是一种功能,它返回指向list_value“链接列表”的指针。create_list t调用插入函数以在链接列表的开头添加新值。 affiche is a function that print the data "integer"
关联是将数据“整数”打印的功能
here: 这里:
#include<stdio.h>
#include<string.h>
struct liste_value
{
int d;
struct liste_value *next;
};typedef struct liste_value LISTE_VALUE;
void insertion(LISTE_VALUE **first,int a)
{
LISTE_VALUE *p;
p=(LISTE_VALUE*)malloc(sizeof(LISTE_VALUE));
p->d=a;
p->next=*first;
*first=p;
}
LISTE_VALUE* create_list()
{ int i;
LISTE_VALUE* first;
for(i=0;i<10;i++)
{
insertion(&first,i);
}
return(first);
}
void affiche(LISTE_VALUE *first)
{ LISTE_VALUE *p=first;
while(p)
{
printf("data = %d\n",p->d);
p=p->next;
}
}
void main()
{
LISTE_VALUE *E;
E=create_list();
affiche(E);
}
The problem is in your create_list
function: 问题出在您的
create_list
函数中:
LISTE_VALUE* create_list()
{ int i;
LISTE_VALUE* first; // <<== Here
for(i=0;i<10;i++)
{
insertion(&first,i);
}
return(first);
}
You do not initialize the first
pointer, but its value is later used in the insertion
as the pointer of the next element of the final node of your list: 你不初始化
first
指针,但其值在以后使用insertion
作为列表的最后一个节点的下一个元素的指针:
void insertion(LISTE_VALUE **first,int a)
{
LISTE_VALUE *p;
p=(LISTE_VALUE*)malloc(sizeof(LISTE_VALUE));
p->d=a;
p->next=*first; // <<== In the first call, *first is uninitialized
*first=p;
}
Add = NULL
to fix this problem: 添加
= NULL
可解决此问题:
LISTE_VALUE* create_list()
{ int i;
LISTE_VALUE* first = NULL; // <<== Fix
for(i=0;i<10;i++)
{
insertion(&first,i);
}
return(first);
}
This function is invalid 该功能无效
LISTE_VALUE* create_list()
{ int i;
LISTE_VALUE* first;
for(i=0;i<10;i++)
{
insertion(&first,i);
}
return(first);
}
variable first was not initialized so it has any arbitrary value. first变量未初始化,因此具有任意值。 You must write
你必须写
LISTE_VALUE* first = NULL;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.