1

I'm very new to coding in C (and therefore the silly exercise I am working on).

I have a linked list, a function that is supposed to print my linked list, and main function.

Unfortunately my knowledge of C is not good enough to understand why this is not printing. What is even more unfortunate is that this code does not crash.

#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node* next; } *Node_t; void print_list(Node_t root) { while (root) { printf("%c ", root->data); root = root->next; } printf("\n"); } int main () { int i; int n = 6; Node_t list = (Node_t)malloc(sizeof(struct Node) * n); Node_t root; for (i=0; i < n; i++) { list[i].data = i+1; if (i == n-1) { list[i].next = 0; } else { list[i].next = &list[i+1]; } } root = &(list[0]); print_list(root); } 
1
  • never cast the result of malloc() Commented Oct 23, 2013 at 10:21

2 Answers 2

1

Your print_list function has the wrong format specifier in printf. It should be

printf("%d ", root->data); 

Corrected code:

void print_list(Node_t root) { while (root) { printf("%d ", root->data); root = root->next; } printf("\n"); } 

And no need to cast result of malloc - this should be fine:

 Node_t list = malloc(sizeof(struct Node) * n); 
Sign up to request clarification or add additional context in comments.

Comments

0

printf("%d ", root->data); instead of printf("%c ", root->data); because you are assigning integer data to list

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.