gpt4 book ai didi

C编程,动态分配+链表

转载 作者:行者123 更新时间:2023-12-03 03:41:21 28 4
gpt4 key购买 nike

我在使用这段代码时遇到了问题,我不确定我做错了什么

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

typedef struct flight_struct{
char flightNum[7];
char originAirport[5];
char destAirport [5];
int timestamp;
struct flight_struct *next;
} flightRec;

int main(){
struct flight_struct *head; // unchanging first node.
struct flight_struct *tail; //the conductor.
struct flight_struct *p; // first new struct
FILE* binFile = fopen("acars.bin","r");
FILE* DataOut;

p =(struct flight_struct*) malloc(sizeof(*p) + 1); //malloc the first struct\

fread(p,sizeof(*p),1,binFile); //read the file into it.

head = p; //make head point to that struct
tail = p; //make tail point to that struct

// fclose(binFile);

while (feof(binFile) == 0){
flight_struct *temp = (struct flight_struct*) malloc(1*sizeof(*temp) + 1); //malloc a new struct
fread(temp,sizeof(*temp),1,binFile); //read the next struct from acars.bin into the structure you malloc'ed
temp -> next = NULL; // add that struct to your linked list using the next memeber of the struct
tail -> next = temp; // set tail to point to the element you just added
tail = tail -> next;
} //while not eof on acars file

tail = head;

while(tail -> next != 0 ){
int t;
t = tail -> timestamp;
time_t tim = t;
printf("%s, %s, %s, %s\n\n",tail -> flightNum,tail -> originAirport,tail -> destAirport,asctime(gmtime(&tim)));
tail = tail -> next;
} //starting at head traverse the list printing the leemnts of each strucure
}

现在,我得到的结果是 What i'm getting

我应该得到的是 What I should be getting

老实说,我不知道我做错了什么,如果能提供帮助就很好了。话虽如此,我无法使用数组,因此链表是唯一的方法。

最佳答案

文件中不应该有指针。

因为文件中元素的顺序自动设置列表中的顺序(显然)。我怀疑该文件包含指向结构的指针,但没关系(指针在不同的体系结构中可能不同,ta-da)。

做什么?

给定数据结构:

struct flight_struct {
char flightNum[7];
char originAirport[5];
char destAirport [5];
int timestamp;
}

实现列表结构:

struct list {
flight_struct* data;
list* next;
list* prev; //if you want bi-directional list
}

并将数据结构从文件加载到列表结构中。

将指针写入二进制文件是错误的,并且可能会导致很多问题。您是自己使用对象创建文件还是从其他来源创建文件?

关于C编程,动态分配+链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29958056/

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