gpt4 book ai didi

c - 如何将字符串从文件传递到链表

转载 作者:太空宇宙 更新时间:2023-11-03 23:54:14 25 4
gpt4 key购买 nike

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct ll
{
char data[50];
struct ll *next;
struct ll *prev;
};
typedef struct ll node;

main()
{
node *head;node *temp1;node *temp2;
head = (node *)malloc(sizeof(node));
temp1 = head;
FILE *p;
int n;
char s[50];
p = fopen("studentRecords.txt","r");
while((fscanf(p, "%s", s)) != EOF)
{
strcpy(head->data, s);
head->next = (node *)malloc(sizeof(node));
head->next = head->next->prev;
head = head->next;
}
head = NULL;
fclose(p);
for(temp2 = temp1; temp2->next != NULL; temp2 = temp2->next)
printf("%s\n", temp2->data);
}

当我运行上面的代码时,输​​出是一个段错误。我该如何纠正这个问题?我将学生的记录作为字符串保存在 studentRecords.txt 文件中。

最佳答案

您在初始化之前使用 next:

head->next = (node *)malloc(sizeof(node));
head->next = head->next->prev; /* head->next->prev is garbage. */
head = head->next; /* Now `head` points nowhere. */

稍后您将取消引用该垃圾值。此外,您正在覆盖刚从 malloc 获得的内存。

关于c - 如何将字符串从文件传递到链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12042270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com