2012-08-13 45 views
0

我有兩個結構和功能引用內存在遞歸循環

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); 
+1

編譯4級警告('/ W4'),看看你得到了什麼警告。 – 2012-08-13 23:17:14

+1

編譯器不會在'string attribute = 5;'那一行吐出來嗎?看到http://ideone.com/xVg0C,但這是海灣合作委員會... – krlmlr 2012-08-13 23:23:00

+0

我想我發現了這個問題 - 遵循這些意見的建議。我爲初始調用(有5個屬性)創建了兩個值「int j = 0」,然後是「string temp =」「',然後將這兩個值用於全部五個值。 – 2012-08-13 23:27:08

回答

0

由貢獻者做出的答案幫助我找到了答案,但他們一直在回答這個問題。

有關設置,功能使用結構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用唯一值更改時,每個屬性都有相應的唯一內存。

0

您是否嘗試過在構造函數中初始化attribute

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

您的代碼看起來有點,但不是完全不像Java的... :-)

+0

有趣,我在C++之前學過java,但不記得java了。 – 2012-08-13 23:31:13

+0

是的,屬性具有來自較早通過樹的值。我在這裏發佈了一個簡化的例子,並沒有完全捕獲我有什麼 – 2012-08-13 23:36:41

+0

不,我沒有嘗試用構造函數初始化,但我會記住這種方法以供將來參考。 – 2012-08-14 00:00:10

0

無參數的函數聲明和函數調用不匹配和功能dosnt具有可變ARG。它也不應該清楚彙編的問題。

+0

是你比較EDIT更新到原始文章? – 2012-08-14 20:28:03

+0

我糾正了問題中的錯誤,屬性有三個參數 - 我使用了一個簡化的例子,並且丟失了一些問題的上下文 – 2012-08-15 16:48:49