在递归循环中条件修改的引用内存

referenced memory conditionally modified in recursive loop

本文关键字:引用 内存 修改 条件 递归 循环      更新时间:2023-10-16

我有两个结构和一个函数

struct nodeT {
bool last;
string attribute1;
string attribute2;
string attribute3;
vector<charT> leafs;
};
struct charT {
char character;
nodeT *next;
};
void addNode(nodeT *n, string stringy, string &attribute1, string &attribute2, string &attribute3)
{
   if (stringy=="") {
      w->last=true;
      return;
   } else {
      if (n->last==true) {
          attribute1=n->attribute1; //these attribute fields were given values earlier
          attribute2=n->attribute2;
          attribute3=n->attribute3;
      }
      addNode(n, stringy.substr(1), attribute);
   }
}

addNode被称为

string test="";
addNode(root, "wordy", test, test, test);

问题是属性引用string &attribute没有更改为 5,它会继续使用 "" 值进行下一次调用。

我尝试将其设置为指针引用*attribute->n->attribute并绑了一个参考&attribute = n->attribute这些是在黑暗中拍摄的,不起作用。

编辑:addNode应该使用单独的内存引用调用。

string test1="";
string test2="";
string test3="";
addNode(root, "wordy", test1, test2, test3);

您是否尝试过在构造函数中初始化attribute

struct nodeT {
   bool last;
   string attribute;
   vector<charT> leafs;
   nodeT() : attribute("5") {}
 };

你的代码看起来有点,但不完全是,不像Java... :-)

函数声明和函数调用的参数不匹配,函数 dosnt 具有变量 arg。它也不应该清除编译障碍。

贡献者做出的答案帮助我找到了答案,但他们的答案与问题略有不同。

对于设置,函数使用结构nodeTcharT并且被调用时相当于

   root is defined globally in the class
   string wordy = "hello";
   string test="";
   addNode(root, "wordy", test, test, test);

addNode应该使用单独的内存引用进行调用。

string test1="";
string test2="";
string test3="";
addNode(root, "wordy", test1, test2, test3);

因此,当以后属性 1、2 和 3 被更改为唯一值时,每个属性都有一个相应的唯一内存。