Search code examples
c++pointersstructnullnullptr

Checking if a pointer in a struct is null


I have a very simple struct

 struct Node{
     Node* pNext;
     int nValue;
 };

and i am trying to always add to the pNext that is not null.

Node *head;


void add(int nValue){
    if (!head)
    {  
        Node *node = new Node;
        node->nValue=nValue;
        head = node;
    }
    else
    {
        add(head,nValue);
    }
}

void add(Node *pNode, int nValue){
    if (!(pNode->pNext))
    {
        Node *node = new Node;
        node->nValue=nValue;
        pNode->pNext = node;
    }
    else
    {
        add(pNode->pNext,nValue);
    }
}

When I call add(10); the first time, it sets the head pointer to an instantiated node. but when I call the method again add(9); i get an "Access violation reading location 0xCDCDCDCD".

My question is, how can i check if the pNext node is assigned an address or not? i tried using the == nullptr but to no avail.


Solution

  • You didn't initialize the pNext pointer, so it has probably some random value.

    Try to use this declaration :

     struct Node{
       //Default constructor, which sets all values to something meaningful
       Node():pNext(nullptr), nValue(0) {}
    
       Node* pNext;
       int nValue;
     };