Reputation: 65
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 -->
Upvotes: 0
Views: 47
Reputation: 121659
Here's an example on a 64-bit Windows host:
test.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node
{
int data;
struct Node *link;
}*head=NULL;
int main(int argc, char* argv[])
{
printf ("sizeof(struct Node): %lld, sizeof(struct Node*): %lld\n",
sizeof(struct Node), sizeof(struct Node*));
return 0;
}
Output:
sizeof(struct Node): 16, sizeof(struct Node*): 8
In other words, you probably want malloc(sizeof(struct Node)
Upvotes: 1