1

I'm new with pointers, and I'm having some problems with a LinkedList in C. Once I return from adding the first node to the list, it says that the root node is still empty. Any help is appreciate!!

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

typedef struct Nodo {
    int x;
    struct Nodo *next;
} Nodo;

int size(Nodo *nodo) {
    if (nodo == 0) {
        return 0;
    }
    int size = 0;
    Nodo *aux = nodo;

    while (aux->next != NULL) {
        aux = aux->next;
        size = size + 1;
    }

    return size;
}

Once I add the first element to the list inside the addNode function, it says that the address is changed.

void addNodo(Nodo *root, Nodo *nodo) {
    if (root == 0) {
        root = nodo;
        printf("New address: %p\n", root);
        return;
    } else {
        Nodo *aux = root;
        while (aux->next != NULL) {
            printf("%d, ", aux->x);
            aux = aux->next;
        }
            printf("%d\n", aux->x);
        aux->next = nodo;
    }
}

int main() {
    Nodo *root;      

    Nodo *sig = (Nodo *) malloc(sizeof(Nodo));
    sig->x = 1;

    Nodo *sig2 = (Nodo *) malloc(sizeof(Nodo));
    sig2->x = 1;

    addNodo(root, sig);

Once I return from the function call, it says that the root node is still empty (0)

    printf("Address: %p\n", root);

    addNodo(root, sig2);

    printf("Size: %d\n", size(root));

}
Alex
  • 11
  • 3
  • Welcome to Stack Overflow! [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Nov 02 '15 at 06:31
  • To add to the linked question, 1) `root` is not initialized, it's not guaranteed to be `NULL` (or `0`, as you used). 2) check the return value of `malloc()` before making use of the pointer. – Sourav Ghosh Nov 02 '15 at 06:37

0 Answers0