首页 文章

检查结构中的指针是否为空

提问于
浏览
1

我有一个非常简单的结构

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

我试图总是添加到非空的pNext .

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

当我打电话给add(10);第一次,它将头指针设置为实例化的节点 . 但是当我再次调用该方法时添加(9);我得到"Access violation reading location 0xCDCDCDCD" .

我的问题是,如何检查pNext节点是否分配了地址?我尝试使用== nullptr但无济于事 .

4 回答

  • 0

    你没有初始化pNext指针,所以它可能有一些随机值 .

    尝试使用此声明:

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

    将您的代码更改为:

    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);
        }
    }
    
  • 0

    你忘了将 head 设置为 NULL 开始,并在新创建的节点中将 pNext 设置为 NULL .

    与例如Java,C不会自动将变量初始化为0(或等效变量) .

  • 0

    你需要通过在 node 的构造函数中显式设置为 nullptr 来正确初始化 pNext . 0xCDCDCDCD 始终是访问未初始化内存的指示符 .

相关问题