Josh
Josh

Reputation: 3321

Linked List - pointers

I created a linked list and when I tried to print values of the nodes and used NULL as a bound, it didn't work. For example:

#include <iostream>

typedef struct Node;
typedef Node* Node_ptr;
struct Node
{
    int i;
    Node_ptr next;
};

int main()
{
    Node_ptr ptr, head;
    ptr = new Node;
    head = ptr;

    // load
    for(int j = 0; j < 4; j++)
    {
        ptr->next = new Node;
        ptr->i = j;
        ptr = ptr->next;
    }

    // print
    ptr = head;
    while(ptr->next != NULL)
    {
        std::cout << "print: " << ptr->i << std::endl;
        ptr = ptr->next;
    }
}

However, when I run this code, the code gets stuck in an endless loop in the while loop. It never understands that the linked list is only 5 nodes long, it just keeps on going. I can't understand why that happens.

Upvotes: 1

Views: 5658

Answers (3)

Luchian Grigore
Luchian Grigore

Reputation: 258668

Try value initializing your Node:

ptr = new Node();

instead of

ptr = new Node;

Otherwise, you'll just have garbage in the members.

Upvotes: 4

Mooing Duck
Mooing Duck

Reputation: 66981

while(ptr->next != NULL)

You clearly coded it to continue until ptr->next is NULL. Maybe you should set ptr->next to NULL for at least one item in the list? This is why it is common in C to memset(&object, 0, sizeof(object));, or in C++ to have a constructor.

typedef struct Node
{
  int i;
  Node* next;
  Node() : i(0), next(NULL) {} //prevents this problem
}

Upvotes: 3

sonicwave
sonicwave

Reputation: 6102

You probably just need to initialize your pointers (to NULL), otherwise they'll just contain garbage, and will thus also appear as being valid pointers.

For instance:

for(j = 0; j < 4; j++)
{
   ptr->next = new Node;
   (ptr->next)->next = NULL;
   ptr->i = j;
   ptr = ptr->next;
}

Upvotes: 5

Related Questions