简体   繁体   中英

unknown value linked list in C

my program supposed to print
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
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. 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:

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:

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:

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. You must write

    LISTE_VALUE* first = NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM