Search code examples
carrayspointersnodes

Making a simple integral list with pointers


I'm trying to create a basic integral list made with Nodes (I should also point that I'm learning pointers by doing this exercise)

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

But it doesn't seem to work. Every time I tried to print the list it shows me random value Here's my code:

Node *head = NULL;  // The head of the list - global


void push(int d) {

    Node newNode;
    if (head == NULL)
    {
        printf("In\n");
        head = &newNode;
        (*head).data = d;
    }
    else
    {
        printf("In2");
        newNode.next = head;
        head = &newNode;
    }

void printList() {
    while (head != NULL)
    {
        printf("In while\n");
        printf("%d",(*head).data);
        head = head->next;
    }
}

when I try to do for example: push(1); and printList() I get: 263958281 or any other random value. Does anyone knows why ?

PS: If I tried to do:

push(1);
push(2);
printList();

my ideal output would be:

2 1

Solution

  • That:

    Node newNode;
    

    Allocates the node on the stack. After the function returns that node exists no more.

    List nodes are normally allocated from the heap with malloc function. Heap-allocated memory persists until it is explicitly deallocated with free.

    E.g.:

    void push(int d) {
        Node* newNode = malloc(sizeof(Node));
        newNode->data = d;
        newNode->next = head;
        head = newNode;
    }