【问题标题】:Checking if a pointer in a struct is null检查结构中的指针是否为空
【发布时间】:2013-09-02 14:54:47
【问题描述】:

我有一个非常简单的结构

 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);第一次,它将头指针设置为实例化节点。但是当我再次调用该方法时 add(9);我收到“访问冲突读取位置 0xCDCDCDCD”。

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

【问题讨论】:

    标签: c++ pointers struct null nullptr


    【解决方案1】:

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

    尝试使用这个声明:

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

    【讨论】:

      【解决方案2】:

      将您的代码更改为:

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

      【讨论】:

        【解决方案3】:

        您忘记在新创建的节点中将head 设置为NULL 以及将pNext 设置为NULL

        相对于例如Java、C++ 不会自动将变量初始化为 0(或等效值)。

        【讨论】:

          【解决方案4】:

          您需要通过在node 的构造函数中将nullptr 显式设置为nullptr 来正确初始化pNext0xCDCDCDCD 始终处于访问未初始化内存的指示器中。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-02-07
            • 2021-07-02
            • 2015-07-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多