I am trying to print the values of the single linked list in c, but its printing the garbage values after printing the values entered. I have written the create function to create the linked list by using the do-while loop, and also the display function to print the linked list. My question is why it is printing the garbage value after entering the values. Please help me to find out where I did wrong in my code to help further my coding practices.
Tried Code:
#include <stdio.h>
#include <stdlib.h>
//Declaring the struct variable
struct Node
{
int data;
struct Node *link;
}*head=NULL;
//Creating the Linked List
void create()
{
char ch= 'y';
do
{
printf("ch : %c",ch);
struct Node *p,*q;
p = (struct Node*)malloc(sizeof(struct Node*));
printf("\nEnter the Data : \n");
scanf("%d", &p->data);
p->link = NULL;
if(head == NULL)
{
head = p;
}
else
{
q->link = p;
}
q=p;
scanf("%c",&ch);
}while(ch!= 'n');
}
//Displaying the Linked List
void display()
{
struct Node *p=head;
if(p == NULL)
{
printf("\n List is Empty \n");
}
else
{
while(p!=NULL)
{
printf("%d -->", p->data);
p = p->link;
}
}
}
int main()
{
printf("\n Enter the data into the linked list: \n");
create();
printf("\nCreation Complete........ Displaying\n");
display();
return 0;
}
Output:
1
2
3
4
5
6
n
Creation Complete........ Displaying
1 --> 2 --> 3 --> 4 --> 5 --> 6 -->7097656 -->
sizeof(struct Node*)is the size of a pointer to a node. You want to allocate a node. Remove the star. While you're at it, remove the cast of the return value ofmalloc. It doesn't help anything and in some circumstances can hide errors.