Using linked list in C
I am new to linked list topic and I just created my first program using linked lists, the problem is that it does not store data in structure. It works fine with no errors, but no data is displayed when printing. Here is my code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
int nID;
char chTitle;
struct node* next;
};
void addList(struct node *head);
void printList(struct node *head);
int checkID(struct node *head, int t);
int main(int argc, const char * argv[])
{
int nInput;
struct node *head = NULL;
while (1)
{
printf("\n\t\t~~MENU~~\n");
printf("1. Add a new book\n");
printf("2. Print all data\n");
printf("3. Exit\n");
printf("Make your selection: ");
scanf("%d", &nInput);
switch (nInput)
{
case 1:
addList(head);
break;
case 2:
printList(head);
break;
case 3:
printf("\nGoodby!!! Thanks for using the program\n");
exit(1);
break;
default:
printf("\n\t\t~~Invalid Input~~\n");
break;
}
}
return 0;
}
void addList(struct node *head)
{
int bookId; // Used to store the BOOK ISBN so it can be checked if it already exist
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
printf("\n Enter Book Details\n");
printf("Enter book ISBN: ");
scanf("%d", &bookId);
int bInd = checkID(head, bookId);
if (bInd == 0)
{
printf("Enter title: ");
scanf("%s", &temp->chTitle);
temp->next = head;
head = temp;
}
else
{
printf("\nSorry another book using that id!\n" );
}
}
void printList(struct node* head)
{
while (head != NULL)
{
printf("%s", &head->chTitle);
head = head->next;
}
}
int checkID(struct node *head, int t)
{
head = NULL;
while (head != NULL)
{
if (head->nID == t)
return 1;
head = head->next;
}
return 0;
}
0
source to share
2 answers
One problem here:
void addList(struct node *head)
addList()
gets a COPY of the head pointer, so when you change it in this function, you only change that local copy. The caller's version is not changed. One way to solve this is to use a double pointer:
void addList(struct node **head)
{
int bookId; // Used to store the BOOK ISBN so it can be checked if it already exist
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
printf("\n Enter Book Details\n");
printf("Enter book ISBN: ");
scanf("%d", &bookId);
int bInd = checkID(*head, bookId);
if (bInd == 0)
{
printf("Enter title: ");
scanf("%s", &temp->chTitle);
temp->next = *head;
*head = temp;
}
else
{
printf("\nSorry another book using that id!\n" );
}
}
Then your caller will change too:
addList(&head);
Also, as @ 5gon12eder mentioned, a char
contains only one character. You need an array to store the header char
:
struct node {
int nID;
char chTitle[100]; /* or how ever long your title can be */
struct node* next;
};
0
source to share