0

C++ で試行を実装しようとしています。これが私が使用した構造です:

typedef struct tries{
    int wordCount;
    int prefixCount;
    map<int,struct tries*> children;
}tries;

初期化メソッド:

void initialise(tries *vertex)
{
    vertex = (tries*)malloc(sizeof(tries*));
    vertex->wordCount = vertex->prefixCount = 0;
    for(char ch='a';ch<='z';ch++)
        vertex->children[ch]=NULL;

}

初期化メソッドにセグメンテーション違反vertex->children[ch]=NULL;あります。障害は次のとおりです。

Program received signal SIGSEGV, Segmentation fault.
0x000000000040139a in std::less<int>::operator() (this=0x604018, 
    __x=@0x21001: <error reading variable>, __y=@0x7fffffffddb8: 97)
    at /usr/include/c++/4.6/bits/stl_function.h:236
236           { return __x < __y; }

なにが問題ですか?

4

1 に答える 1

6

malloc()C++ を使用している場合は使用しないでください。sizeof(tries*)また、のサイズのオブジェクトを作成する必要がある場合は、ポインタ ( ) を保持するのに十分なメモリを割り当てないでくださいtries

new次の演算子を使用します。

vertex = new tries();

または、まったく使用せずnew、生のポインターを使用した手動のメモリ管理を避け、代わりにスマート ポインターの使用を検討してくださいnewdelete.

また、C++ クラスにはコンストラクターがあるため、initialise()メソッドは実際にはコンストラクターに置き換えることができますtries

struct tries
{
    tries() : wordCount(0), prefixCount(0) 
    {
        // ...
    }

    int wordCount;
    int prefixCount;
    map<int, struct tries*> children;
};
于 2013-05-03T15:11:12.007 に答える