0

次の挿入位置を指すポインタを使用して単純なリンク リストを作成し、ノードを 1 つずつ追加しようとしています。

Tnode* NULL_cp = 0;
struct Tnode{
 string word;
 Tnode* left;
 Tnode* right;
};


int main(int argc, char** argv){
 int n = 0;
 Tnode head;
 head.word = "the head";
 head.left = NULL_cp;
 head.right = NULL_cp;
 Tnode* insertP = &head;
 while(n<argc-1){
  Tnode node;
  node.word = argv[n+1];
  node.left = insertP;
  node.right = NULL_cp;
  insertP->right = &node;
  insertP = &node;
  cout << "inside loop: " << insertP->word <<  endl;
  n++;
 }
 cout << "outside loop: the word is " << insertP->word << endl;
}

出力は

inside loop: hello
outside loop: the word is

a.out helloと入力した場合。私を混乱させたのは、1回のループの後、insertPがhelloという単語を持つ新しく挿入されたノードを指しているはずですが、ループ内でhelloを出力したにもかかわらず何も出力しなかったことです。どうもありがとうございました

4

1 に答える 1

2

問題を最小限に抑えましょう。

while(n<argc-1)
{
   Tnode node;
   //...
}

範囲外にnodeなると、そのstd::stringメンバーも範囲外になります。ツリー内のノードへのポインターがぶら下がります。オブジェクトがまだ生きているため、ループ内では機能します。外では… それほどでもありません。

ダイナミック アロケーションを使用する:

while(n<argc-1){
  Tnode* node = new Tnode;
  node->word = argv[n+1];
  node->left = insertP;
  node->right = NULL_cp;
  insertP->right = node;
  insertP = node;
  cout << "inside loop: " << insertP->word <<  endl;
  n++;
}

そして最後に忘れないdeleteでください。

于 2012-05-30T20:25:42.297 に答える