gusgxrha gusgxrha - 2 months ago 5
C Question

Printing linked lists in C

I am currently in the process of learning C and am now studying linked lists. I think I wrapped my head around the most basic concepts. Now I would like to print such a list. I implemented my own method to print the contents of the list but they were semi-efficient. I found learn-c.org and liked their method of doing it a lot but I seem unable to make use of it.

Their method is the following:

void print_list(node_t * head) {
node_t * current = head;

while (current != NULL) {
printf("%d\n", current->val);
current = current->next;
}
}


I created a node named "head"

node_t * head = malloc(sizeof(node_t));


and tried calling the method with "head" as an argument which is - apparently - wrong. Means:
print_list(head)
shows me an "conflicting types" error.

Anyone got any input on that? I tried around already and from my understanding the method expects a pointer to a node_t structure.

Edit: Full code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct node {
int val;
struct node * next;
} node_t;

int main(){
node_t * head = malloc(sizeof(node_t));
if (head == NULL) {
return 1;
}

head->val = 1;
head->next = NULL;

print_list(head);

}

void print_list(node_t * head) {
node_t * current = head;

while (current != NULL) {
printf("%d\n", current->val);
current = current->next;
}
}

Answer

When you call print_list the compiler doesn't know what it is. You must declare everything you use, before you use it.

So something like

// Declare the function prototype, so compiler knows about it
void print_list(node_t * head);

int main(void)
{
    node_t * head;

    // Create and populate list...

    print_list(head);

    return 0;
}

// Define the function implementation
void print_list(node_t * head)
{
    // The implementation of the function...
}
Comments