I am creating a telephone directory app in C and have encountered problems printing the strings in the linked list (firstname and lastname), as seen in the display function. The 'number' integer is printing but the strings are not. I would greatly appreciate your help. Thanks.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>
struct node {
char *firstname;
char *lastname;
int *number;
struct node *next;
}*head;
struct node *start=NULL;
struct node *getnode() {
return((struct node *)malloc(sizeof(struct node)));
}
void display() {
struct node *temp;
temp=start;
if(temp!=NULL) {
printf("%s \n", temp->firstname);
printf("%s \n", temp->lastname);
printf("%d \n", temp->number);
temp=temp->next;
} else {
printf("Please create an entry\n");
}
}
void insert() {
struct node *temp,*nn;
nn=getnode();
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
printf("Enter First name:\n");
scanf("%s",&nn->firstname);
printf("Enter Last name:\n");
scanf("%s",&nn->lastname);
printf("Enter number:\n");
scanf("%d",&nn->number);
temp->next=nn;
nn->next=NULL;
display(start);
}
struct node *create() {
struct node *temp,*nn;
if(start!=NULL) insert();
else {
nn=getnode();
start=nn;
temp=start;
printf("Enter First name:\n");
scanf("%s",&nn->firstname);
printf("Enter Last name:\n");
scanf("%s",&nn->lastname);
printf("Enter number:\n");
scanf("%d",&nn->number);
nn->next=NULL;
}
}
scanf
function expects the arguments for%s
to bechar *
. The argument&nn->firstname
has the typechar **
which is wrong and leads to undefined behavior. Same withlastname
.