c - 链表相同的值
问题描述
我正在尝试理解 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);
}
解决方案
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';
推荐阅读
- r - 如何根据应用于大量列的“不等于”标准对数据框进行子集化?
- angularjs - Chrome 插件和网络应用程序 keycloak 之间的共享会话
- fullcalendar - 完整的日历将 fc-heading 和 fc-item 包装到单个 div
- php - PHPUnit 在断言失败时运行回调
- amazon-web-services - 如何将每个请求从 CloudFront 转发到源 S3
- r - 将特定文件名分配给 rmarkdown 中的不同输出文件集
- c# - 如何使用 linq 检查值是否为 NULL
- three.js - 为球体几何体的某些面设置透明(不透明度:0)
- c - 在 C 中,我在将文件中的元素从最大到最小排序的算法上遇到问题
- go - Go 中多字结构类型的命名标准是什么?