我正在使用链接列表来保存表示ASCII字符的结构。我能够从文件中读取输入并打印回去,所以我知道我有需要的数据。在将节点添加到列表中并尝试打印列表以确保节点被填充后,程序突然结束,但是我不明白为什么。我的输入文件目前只有一行。 (例如111B1111)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#ifndef NULL
#define NULL 0
#endif
// Define a struct to be used in the linked list
typedef struct tape {
int ch;
struct tape *next_rec;
struct tape *prev_rec;
} tape;
// Typedef for the structure pointer
typedef tape *TAPEPTR;
// Define a struct to hold the transition instructions
typedef struct instruction {
int write;
int direction;
int new_state;
} instruction;
// Variables
int num_states;
int start_state;
int end_state;
char filename[20];
FILE *fp;
// Add ASCII character to linked list
TAPEPTR build_list(int size, char *input) {
TAPEPTR head = NULL;
int i = 0;
int ch;
while (i++ < size) {
ch = input[i];
TAPEPTR new_rec = NULL;
TAPEPTR tmp_rec = NULL;
TAPEPTR prev_rec = NULL;
// Allocate memory for the list item
new_rec = (TAPEPTR)malloc(sizeof(tape));
if (!new_rec) {
printf("\nUnable to allocate memory!\n");
exit(1);
}
// Set the new link's data
new_rec->ch = ch;
new_rec->next_rec = NULL;
new_rec->next_rec = NULL;
//Adding first item to the list
if (head == NULL) {
head = new_rec;
new_rec->next_rec = NULL;
new_rec->prev_rec = NULL;
} else {
// Adding item at the end of the list
tmp_rec = head->next_rec;
prev_rec = head;
while (tmp_rec->next_rec != NULL) {
tmp_rec = tmp_rec->next_rec;
prev_rec = prev_rec->next_rec;
}
tmp_rec->next_rec = new_rec;
new_rec->prev_rec = tmp_rec;
new_rec->next_rec = NULL;
}
}
return head;
}
// Display the linked list
void show_list(TAPEPTR head) {
TAPEPTR cur_ptr = head;
while (cur_ptr != NULL) {
printf("\n%d", cur_ptr->ch);
}
cur_ptr = cur_ptr->next_rec;
}
// Setup turing machine
void load(FILE* fp) {
char buf[256];
// Read text until newline
fscanf(fp, "%[^\n]", buf);
int length = strlen(buf);
printf("Data from the file: \n%s", buf);
// Create a doubly-linked list and store nodes as type struct tape
TAPEPTR head = build_list(length, buf);
// Print out the linked list
show_list(head);
//fclose(fp);
}
int main(void) {
// Ask the user for the input file
printf("\nEnter the name of the input file: ");
gets(filename);
// Open the input file for reading
if ((fp = fopen(filename, "r")) == NULL) {
fprintf(stderr, "Error opening file.\n");
exit(1);
}
// Build the Turing Machine
load(fp);
return 0;
}