I am trying to write a program to make a list of books using linked list. I am using C language. My program crashes as soon as I finish entering the list. It is supposed to print the list before exiting. Any ideas ?
//Defining what libraries should be included.
#include <stdio.h>
#include<string.h>
//Defining the linked list structure
typedef struct node
{
void *data_ptr;
struct node *link;
} NODE;
// Create node function
NODE *create_node (void *item_ptr)
{
NODE *n_ptr;
// Allocate a node in dynamic memory.
n_ptr = (NODE *) malloc (sizeof (NODE));
n_ptr->data_ptr = item_ptr;
n_ptr->link = NULL;
return n_ptr;
}
//Function main begins program execution
int main (void)
{
//Definning variables
int *new_data;
int *node_ptr;
NODE *node, *head;
char bookTitle[20];
int x;
//Tells the user how to exit the program.
printf("Enter 'end' to stop the program\n");
printf("Enter the title of the book : ");
scanf("%s",bookTitle);
while (strcmp(bookTitle,"end") != 0)//Beginning of while loop
{
// Allocate memory and create data to pass to the node
new_data = (void *) malloc (sizeof (char)*20);
*new_data = bookTitle;
// Calling the create_node function with data that was just created.
node = create_node (new_data);
// Link it to the previous node when created.
node->link = create_node(new_data);
// Create a head node to keep track of the beginning of the list
head = node;
printf("Enter the title of the book : ");
scanf("%s",bookTitle);
}
// Transverse the list and print
x = 0;
if (node == NULL)//Check whether the list is empty
{
printf("\nThe list is empty");//Print error
}
else
{
while (node != NULL)//While loop to print the list
{
x++;
printf ("\nThe title of the book is: %s", *((char *) node->data_ptr));
node = node->link;
}
}
system ("PAUSE");
return 0;// indicate the program ended successfully
}// end of fucntion main