gpt4 book ai didi

打印后文件中的 C 链接列表不存在

转载 作者:行者123 更新时间:2023-11-30 19:38:53 25 4
gpt4 key购买 nike

所以,我必须从文件输入打印一个链接列表,我已经成功地让它工作了:

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

typedef struct Vehicle{
int option;
char make [30];
char model[30];
int car_manufacture_date;
float maximum_velocity;
float mass;
int seats;
struct Vehicle *next;//linked list node
} vehicle_t;


int main (){

FILE* fp;
fp = fopen("vehicles.crash.txt", "r");

vehicle_t* first_car = malloc(sizeof(vehicle_t));
if (first_car == NULL){
printf("Error. Failed to allocate memory to first_car\n");
exit(1);
}
vehicle_t* current_vehicle = malloc(sizeof(vehicle_t));
if (current_vehicle == NULL){
printf("Error. Failed to allocate memory to current_vehicle\n");
exit(1);
}
vehicle_t* new_vehicle = malloc(sizeof(vehicle_t));
if (new_vehicle == NULL){
printf("Error. Failed to allocate memory to new_vehicle\n");
exit(1);
}
printf("GOOD1\n");

current_vehicle = first_car;
new_vehicle = first_car;
printf("GOOD2\n");

//Loading vehicles from file to linked list
if (fp != NULL)
{
printf("GOOD3\n");
while (fscanf(fp,"%d %s %s %d %f %f %d", &new_vehicle->option, new_vehicle->make, new_vehicle->model, &new_vehicle->car_manufacture_date,
&new_vehicle->maximum_velocity, &new_vehicle->mass, &new_vehicle->seats) != EOF)
{
printf("GOOD4\n");
current_vehicle->next = new_vehicle;
current_vehicle = current_vehicle->next;
new_vehicle = malloc(sizeof(vehicle_t));
if (first_car == NULL){
printf("Error. Failed to allocate memory\n");
new_vehicle->next=NULL;
exit(1);
}

printf("GOOD5\n");
}
close(fp);
printf("Input completed\n");
}
else
printf("Error! couldn't find file\n");

current_vehicle = first_car;

while (current_vehicle != NULL)
{
printf("Option: %d\tMake: %s\tModel: %s\tManufactured: %d\tMax Velocity: %.2f\tMass: %.2f\tSeats: %d\n",
current_vehicle->option, current_vehicle->make, current_vehicle->model, current_vehicle->car_manufacture_date,
current_vehicle->maximum_velocity, current_vehicle->mass, current_vehicle->seats);

new_vehicle = current_vehicle->next;
current_vehicle = current_vehicle->next;
};
printf("Printing completed");
return 0;
}

一切正常,直到打印出最后一个文件项,之后程序崩溃。从我在其他帖子中看到的内容来看,while 循环与它们全部匹配。

打印的“GOOD”语句只是检查点

文件中的文本格式为:1 Toyota Camry 2010 200.0 1100.0 5

最佳答案

我认为您忘记将最后一个列表节点的 ->next 字段设置为 NULL。您刚刚调用了 malloc,因此该值可能是任意随机值,从而导致打印失败。

关于打印后文件中的 C 链接列表不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37403294/

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