首页 > 解决方案 > 链表相同的值

问题描述

我正在尝试理解 C 中的链表。所以我正在尝试编写一个程序,该程序将从文件中读取并创建一个链表。但是我遇到了一个我找不到原因的障碍。虽然我只将头值节点 *h 设置为 n 一次,但看起来该值会自动更改为 n 的下一个值。为了检查我最后使用了 printf 。他们都返回相同的结果。有人可以帮忙吗?

PS - 这是我第一次使用 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);
}

标签: cpointerslinked-list

解决方案


name结构中的成员node只是一个指向字符串(字符数组)的指针。您分配名称的每个节点都指向相同的字符数组:

char characters[45];

您应该为任何节点分配字符数组:

#define MAX_LEN 45
typedef struct node
{

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

并复制字符串:

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

推荐阅读