Willy
Willy

Reputation: 15

How can I display the data I created in a linked list?

I think there is something wrong with my create.

void add(N *p) {
    N *current, *start;
    current = malloc(sizeof(p));
    scanf("%d", &current->data);
    current->next = NULL;

    if (p == NULL) {
        p = current;
        start = current;
    } else {
        start->next = current;
        start = current;
    }
}

I think that my display() is correct.

void display(N *p) {
    N *current;
    current = p;
    while (current != NULL) {
        printf("\n%d", current->data);
        current = current->next;
    }
}

Upvotes: 0

Views: 30

Answers (2)

chqrlie
chqrlie

Reputation: 144969

There are problems:

  • function add() does not allocate the correct amount of memory. Use this method:

    current = malloc(sizeof(*current));
    
  • The way you are inserting the newly allocated object into the list does not work: you modify p, which is an argument with local scope, and you set start which also has local scope. No side effect is performed on the N pointer is the callers scope.

  • Your display function is correct, but I would favor adding the newline at the end of the output instead of at the beginning.

Here is an updated version with a better API:

int add(N **headp) {
    N *current = calloc(sizeof(*current));
    if (current == NULL) {
        fprintf(stderr, "cannot allocate memory for new object\n");
        return -1;
    }
    if (scanf("%d", &current->data) != 1) {
        fprintf(stderr, "cannot read value for new object\n");
        return -2;
    }
    current->next = *headp;
    *headp = current;
    return 0;
}

void display(const N *list) {
    for (const N *p = list; p != NULL; p = p->next) { 
        printf("%d\n", p->data);
    }
}

The add function is used this way from the caller:

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

typedef struct N {
    int data;
    struct N *next;
} N;

int main(void) {
    N *list = NULL;

    for (i = 0; i < 10; i++) {
        if (add(&list))
            break;
    }
    display(list);
    return 0;
}

Upvotes: 0

chrisaycock
chrisaycock

Reputation: 37928

Your malloc(sizeof(p)) only returns enough space for a pointer. You instead want malloc(sizeof(N)).

Also, you need to return the new value of p instead of throwing it away at the end of add(). (Your start has a similar issue; pick one to be the head of your linked list.)

Upvotes: 1

Related Questions