DaRoli
DaRoli

Reputation: 3

linked list missing element

I am writing a c program where I want to add strings to a linked list based on a condition. As my code is rly long I made a simplified version which also shows my problem.

My problem is that after filling the list with strings, when I want to print all the elements, my "go_thru" function fails to print the last element of the list. The code:

#include <stdio.h>
#include <stdlib.h>

typedef struct listelement{
    char val[100];
    struct listelement *next;
} LISTELEMENT;

void go_thru( LISTELEMENT *head ){
    LISTELEMENT *temp = head;

    while( temp != NULL ){
        printf("%s ", temp->val);
        temp = temp->next;
    }
}

LISTELEMENT *insert_before( LISTELEMENT *head, char value[] ){
    LISTELEMENT *new_el = ( LISTELEMENT* ) malloc( sizeof( LISTELEMENT ) );

    strcpy( new_el->val, value );
    new_el->next = head;

    return new_el;
}

int main()
{
    LISTELEMENT *list_chi = NULL;
    int i;
    char arr[6][10] = { "cheese",
                        "salt",
                        "icecream",
                        "snow",
                        "summer",
                        "violet"    };
    for( i = 0; i < 6; i++ )
        list_chi = insert_before( list_chi, arr[i] );

    go_thru( list_chi->next );

    return 0;
}

The output contains all the strings except "violet". I google-d a lot, looking for an answer, even tried to search here btw the questions, but still could not manage to solve the problem :/

Upvotes: 0

Views: 300

Answers (1)

By the time the for-loop in main finishes, your list looks something like:

"violet" -> "summer" -> "snow" -> "icecream" -> "salt" -> "cheese" -> [NULL]
/* where -> is a 'next' */

(The reverse ordering is due to the use of insert_before.) With that in mind, the problem is:

go_thru(list_chi->next); /* ERROR: skips first element! */

Why? Well, to use that diagram again:

   "violet"    -> "summer"      -> "snow" -> "icecream" -> "salt" -> "cheese" -> [NULL]
/* ^^ list_chi    ^^ list_chi->next */

You can fix that by calling go_thru(list_chi) instead. Other than that, your code looks good.

Upvotes: 1

Related Questions