Bro Nick Bro Nick - 1 month ago 11
C Question

C linked list to Display contents

Is there any part i have missed in the code?

I am creating a non-empty linked
list and to display the contents of a linked list. Where am I getting it wrong?

#include <stdbool.h>
#include <stdlib.h>
struct node_int
{
void *data;
node next;
};
typedef struct node_int *node;
typedef struct list_int { node first; } *list;


void init_list(list *lp, void *o)
{
*lp = (list)malloc(sizeof(struct list_int));
(*lp)->first = NULL;
(*lp)->first->data = o;
(*lp)->first->next = NULL;
}
void print(list ell, void (*print_data)(void *d))
{
list c;
c = ell;
while (c!NULL)
{
print_data(c->data);
c = ell;
}
}

Answer

There are a few problems with your code.

First like to say that I find it bad style to typedef a pointer. If you do that, you should at least use a name which clearly tells that the type is a pointer. Names like list and node make others think of something which is not pointers.

Below is some code showing how it could look without typedef'ed pointers.

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

struct node_int
{
    void *data;
    struct node_int* next;
};

typedef struct node_int node;
typedef struct list_int { node* first; } list;


void init_list(list** lp, void *o)
{
    // Allocate the list
    *lp = malloc(sizeof(list));
    if (*lp == NULL) return;

    // Allocate the first node
    (*lp)->first = malloc(sizeof(node));
    if ((*lp)->first == NULL)
    {
        free(*lp);
        *lp = NULL;
        return;
    }

    // Initialize first element
    (*lp)->first->data = o;
    (*lp)->first->next = NULL;
}

void print(list* ell, void (*print_data)(void *d))
{
    if (ell == NULL) return;

    node* p = ell->first;
    while (p != NULL)
    {
        print_data(p->data);
        p = p->next;
    }
}

void myPrint(void* d)
{
  int* p = (int*)d;
  printf("%d\n", *p);
}

void free_list(list* ell)
{
    // Add code here ...
}

int main(void)
{
    int a = 1;
    list* myList;
    init_list(&myList, &a);
    if (myList == NULL) return 0;

    // Use the list.....
    print(myList, myPrint);

    free_list(myList);
    return 0;
}