Rakibul Hasan
Rakibul Hasan

Reputation: 13

Linked list same value

I am trying to understand the linked list in C. So i am trying to write a program which will read from a file and create a linked list. But I hit a roadblock which I couldn't find a reason why. Although I set the head value node *h to n only one time it looks like the value is automatically changing to the next value of n. To check I used printf at the end. All of them are returning the same result. Can anyone help please?

P.S - This is my first time using stackoverflow.

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

typedef struct node
{
    char *name;
    struct node *next;
} node;

int main (void)
{
    //load the file.
    FILE *fp = fopen("dictionary.txt", "r");
    if (fp == NULL)
    {
        printf("Unable to open the file\n");
    }

    char characters[45];

    //initialize the linked list.
    node *n , *t, *h;
    int flag = 0;

    while(fgets(characters, 45, fp) != NULL)
    {
        //define node for n
        n = malloc(sizeof(node));
        if (n == NULL)
        {
            printf("Out of memory!!!");
        }

        //set the value of n
        n -> name = characters;

        //set the temp & head value to n first time
        if (flag == 0)
        {
            t = n;
            h = n;
        }

        //set the temp -> next value to n after first time
        else
        {
            t -> next = n;
        }

        flag = 1;
    }
    printf("%s\n", h -> name);
    printf("%s\n", t -> name);
    printf("%s\n", n -> name);
}

Upvotes: 1

Views: 474

Answers (1)

nivpeled
nivpeled

Reputation: 1838

name member in your node struct is only a pointer to a string (character array). each node you assign name to point to the very same character array:

char characters[45];

you should allocate the character array for any node:

#define MAX_LEN 45
typedef struct node
{

    char name[MAX_LEN];
    struct node *next;
} node;

and copy the string:

//set the value of n
        strncpy(n -> name,characters, MAX_LEN);
// ensure null terminated
n->name[MAX_LEN-1] = '\0';

Upvotes: 1

Related Questions