3

以下の15行目でポインタ変数*tempを使用して新しいNodeオブジェクトを作成しようとすると、セグメンテーション違反が発生します。私はまだc++と、特に&と組み合わせて使用​​した場合のダブルポインターのしくみにかなり慣れていません。助けてくれてありがとう。

void bst::insert(int n) {
    Node **temp;
    Node *r, *parent;
    // Tree is empty
    if (root == NULL) {
        root = new Node;
        root->parent = NULL;
        root->value = n;
        root->left = NULL;
        root->right = NULL;
        root->isBlack = true;
    } else {
        r = root;
        // Create a node with the given value, n
        (*temp) = new Node;
        (*temp)->value = n;
        (*temp)->left = NULL;
        (*temp)->right = NULL;
        (*temp)->isBlack = false;
4

3 に答える 3

5

変数tempは初期化されていません。したがって、逆参照tempする値がないため、逆参照の試行は失敗します。ポインタへのポインタが本当に必要な場合は、シングルポインタを宣言し、&演算子を使用してダブルポインタを取得できます。

于 2012-11-16T01:51:51.310 に答える
2

temp有効なものを指していないので、

(*temp) = new Node;
(*temp)->value = n;
(*temp)->left = NULL;
(*temp)->right = NULL;
(*temp)->isBlack = false;

-statementのelseブランチでは、ポインター変数を逆参照するときに未定義の動作を呼び出します。iftemp

于 2012-11-16T01:52:14.937 に答える
1

ここではダブルポインタ(または私がそれらを呼び出すことを好むのでポインタからポインタ)を使用したくないようです。 temp初期化されないポインタのアドレスを保持します。したがって、を作成new Nodeしようとすると、初期化されたランダムデータに関係なく作成しようとしますtemp

通常のポインタを使用することもできますが、後でポインタをポインタにする必要がある場合は、次を使用して&tempください。

Node * temp;

// <snip>

temp = new Node;
Node->value = n;
//  etc.

SomeFunc( &temp );  //  temp will be passed as a pointer-to-pointer (Node**).

あるいは、tempがポインタからポインタのままであると主張する場合は、次を使用できます。

Node * temp2 = new Node;  // Creates a new Node and assigns the address to temp2
temp = &temp2;            // Assigns the address of the pointer to the Node (temp2) to temp.

//  Now do stuff.

次のように削除する必要があることを忘れないでください。

delete( *temp );
于 2012-11-16T12:20:00.020 に答える