Pergunta

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.

Foi útil?

Solução

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;
 };

Outras dicas

Change your code to:

Node *head;


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

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

You're forgetting both to set head to NULL to begin with, and to set pNext to NULL in your newly created nodes.

As opposed to e.g. Java, C++ doesn't automatically initialize variables to 0 (or the equivalent).

you need to initialize pNext properly by setting it to nullptr explicitly in node's constructor. 0xCDCDCDCD is always in indicator for accessing uninitialized memory.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top