Home > Back-end >  Why is (null) being printed in my c code?
Why is (null) being printed in my c code?

Time:05-30

I am trying to add strings to a linked list but I have a problem with (null) being printed. Anyone who can help me?

The best I could do is narrow it down to this being the problem:

struct node *head = malloc(sizeof(struct node));
struct node *ptr = malloc(sizeof(struct node));

Here is the code:

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

struct node {
    char *data;
    struct node *link;
};

struct node *add_begin(char *d, struct node *head) {
    struct node *ptr = malloc(sizeof(struct node));
    ptr->data = d;
    ptr->link = head;
    return ptr;
}

void add_end(struct node *point, char *data) {
    struct node *temp = malloc(sizeof(struct node));
    
    temp->data = data;
    temp->link = NULL;
    
    while (point->link != NULL) {
        point = point->link;
    }
    point->link = temp;
}

int main() {
    struct node *head = malloc(sizeof(struct node));
    struct node *ptr = malloc(sizeof(struct node));
    head->link = ptr;
    char *data = "Chocolate Cake";
    head = add_begin(data, head);
    add_end(ptr, data);
    while (head != NULL) {
        printf("%s \n", head->data);
        head = head->link;
    }
}

Output:

Chocolate Cake
(null) 
(null) 
Chocolate Cake 

CodePudding user response:

The problem is you allocate dummy nodes, which are uninitialized and happen to have null pointers as data and link. The list should be initially empty, ie: head should be a null pointer.

Note that add_end should also return the head pointer in case an empty list was passed. Passing the arguments in the same order to both functions is highly recommended.

Here is a modified version:

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

struct node {
    char *data;
    struct node *link;
};

struct node *add_begin(struct node *head, char *data) {
    struct node *ptr = malloc(sizeof(*ptr));
    ptr->data = data;
    ptr->link = head;
    return ptr;
}

struct node *add_end(struct node *head, char *data) {
    struct node *ptr = malloc(sizeof(*ptr));

    ptr->data = data;
    ptr->link = NULL;

    if (head == NULL) {
        return ptr;
    } else {
        struct node *temp = head;
        while (temp->link != NULL) {
            temp = temp->link;
        }
        temp->link = ptr;
        return head;
    }
}

int main() {
    struct node *head = NULL;
    char *data = "Chocolate Cake";

    head = add_begin(head, data);
    head = add_end(head, data);

    for (struct node *ptr = head; ptr; ptr = ptr->link) {
        printf("%s\n", ptr->data);
    }
    return 0;
}

Output:

Chocolate Cake
Chocolate Cake
  • Related