Reputation:
Im trying to print variables that assigned in the nodes but it prints random data.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node * next;
};
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head -> data = 1;
head -> next = second;
second -> data = 2;
second -> next = third;
third-> data = 3;
third -> next = NULL;
printf("%d",head);
printf("\n%d",second); //problem in this part
printf("\n%d",third);
return 0;
I'm expecting an output like 1,2,3 which are variables that I assigned to.
Upvotes: 0
Views: 39
Reputation: 906
You are printing the pointer, i.e. the address of those structures. if you want to print data you should print the data field:
printf("%d", head->data);
also, if you want to print out all the elements of a singly linked list, you can do this:
struct Node* p = head;
while (p != NULL)
{
printf("%d\n", p->data);
p = p->next;
}
Upvotes: 1