2

This is my first link list program in C, I am trying to initialize the values of the nodes and trying to print it. however, its not giving me the intended output. Can anyone let me know where am I going wrong?

#include<stdio.h> #include<stdlib.h> struct node { int key; struct node *next; }; typedef struct node NODE; int main () { NODE a,b,c; NODE *list; list=&a; list->key = 10; list->next = &b; list->next->key=20; list->next->next=&c; list->next->next->key=30; list->next->next->next=NULL; printf("%d %d %d", a,b,c); return 0; } 

It prints 10 and 20 with some garbage in between.

1
  • 1
    The garbage is the struct node *next pointer, and probably some padding bits Commented Feb 20, 2014 at 10:09

2 Answers 2

5

You really shoulnd't be passing entire structures (the variables a, b and c) to printf() like that, did that even compile?

You want to pass the integer data:

printf("%d %d %d\n", a.key, b.key, c.key); 

but of course that totally ignores the links between the nodes.

It would more "interesting", in this context, to have something like:

static void print_list(const NODE *head) { const NODE *prev = NULL; for(; head != NULL; prev = head, head = head->next) printf("%d ", head->key); puts(prev != NULL ? "\n" : ""); } 

And then call that from main() after setting list:

print_list(list); /* or print_list(&a); */ 

You can also simplify the creation of the linked list:

a.key = 10; a.next = &b; b.key = 20; b.next = &c; c.key = 30; c.next = NULL; list = &a; 

This more clearly uses the fact that all nodes are directly available, and drops the hysterical link-following.

Sign up to request clarification or add additional context in comments.

Comments

3

You want to print the values of the 3 structures, that are in the field key of each of them. So you need to change the line

printf("%d %d %d", a,b,c); 

with the line

printf("%d %d %d", a.key,b.key,c.key); 

It is actually strange that you do not get a warning from the compiler, like this one:

main.c:20:31: warning: format specifies type 'int' but the argument has type 'NODE' (aka 'struct node') [-Wformat] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.