下面这段代码是网上找来的,很是经典

43 bool GetNodePointerByName(TiXmlElement* pRootEle, const char* strNodeName,TiXmlElement** destNode)
 44 {
 45     // if equal root node then return
 46     if (0 == strcmp(strNodeName, pRootEle->Value()))
 47     {
 48         *destNode = pRootEle;
 49         return true;
 50     }
 51 
 52     TiXmlElement* pEle = pRootEle;
 53     for (pEle = pRootEle->FirstChildElement(); pEle; pEle = pEle->NextSiblingElement())
 54     {
 55         // recursive find sub node return node pointer  
 56         if (0 != strcmp(pEle->Value(), strNodeName))
 57         {
 58             GetNodePointerByName(pEle,strNodeName,destNode);
 59         }
 60         else
 61         {
 62             *destNode = pEle;
 63             printf("destination node name: %s\n", pEle->Value());
 64             return true;
 65         }
 66     }
 67 
 68     return false;
 69 }

其中用到了递归的思想

下面来谈下关于参数中指针的指针的使用。

其实在网上找的代码原本是

43 bool GetNodePointerByName(TiXmlElement* pRootEle, const char* strNodeName,TiXmlElement* &destNode)
 44 {
 45     // if equal root node then return
 46     if (0 == strcmp(strNodeName, pRootEle->Value()))
 47     {
 48         destNode = pRootEle;
 49         return true;
 50     }
 51 
 52     TiXmlElement* pEle = pRootEle;
 53     for (pEle = pRootEle->FirstChildElement(); pEle; pEle = pEle->NextSiblingElement())
 54     {
 55         // recursive find sub node return node pointer  
 56         if (0 != strcmp(pEle->Value(), strNodeName))
 57         {
 58             GetNodePointerByName(pEle,strNodeName,destNode);
 59         }
 60         else
 61         {
 62             destNode = pEle;
 63             printf("destination node name: %s\n", pEle->Value());
 64             return true;
 65         }
 66     }
 67 
 68     return false;
 69 }

不同的地方已经用红色标出

首先先来说下什么时候使用二级指针

想像这么一个场景,现在有一个查询的函数,查到之后会返回一个结构的指针,此时我们可以定义一个该结构的空指针,然后用这个指针来保存这个结果。

那么现在需求变一下,我像把一个该结构的空指针作为一个参数传过去,该函数的返回值另有其他用途,那么这个时候传参数就有上述的两种方法

第一 传指针的地址,所以形参是二级指针

第二 传指针的引用(不知道术语准不准确),指针也是变量,所以就可以有引用(别名),修改别名的值,那么相应的原值也会发生变化。

相关文章:

  • 2022-12-23
  • 2021-10-05
  • 2021-09-06
  • 2021-08-25
  • 2021-07-15
  • 2021-11-29
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-15
  • 2021-07-16
  • 2021-04-03
  • 2022-02-13
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案