C编程,动态分配+链表

标签 c linked-list

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

#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/

相关文章:

无法弄清楚答案是如何得出的

C 编程中的代码安全(避免任何分段/错误)

c++ - bool 运算符缺少模板参数?

java - 为什么我会收到 ConcurrentModificationException?

c - 单链表数组不会删除节点

c - 如何使用linux内核列表实现队列?

c - 在 Linux 中关闭应用程序的 Shell 脚本

c - 调试时指针分配不起作用

c - 二维字符数组中字符的额外打印

C11 _Generic c 程序和 Eclipse c/c++ 上的错误