2017-07-18 27 views
-1

私は電話番号を格納するためにTrieを作成しようとしています。そうしている間、私はすべての異なる番号を格納するために必要なノードの数を数えます。ここで予想外のセグメント化エラー

はコードです:

#include <iostream> 
#include <string> 
#include <vector> 
#include <algorithm> 

using namespace std; 

class Node{ 
    public: 
     char number; 
     vector<Node*> followings; 

     Node(){ 
     number = ' '; 
    } 
     Node(char n){ 
     number = n; 
     followings.resize(10); 
    } 
}; 

int main() 
{ 
    int N; 
    cin >> N; cin.ignore(); 
    Node aux(' '); 
    Node* root = &aux; 
    Node* node; 
    int counter = 0; 
    for (int i = 0; i < N; i++) { 
     string telephone; 
     cin >> telephone; cin.ignore(); 
    node = root; 
     for(int j = 0; j < telephone.size(); j++){ 
      if(node->followings[(int)telephone[j]-48]->number == ' '){ 
       Node aux(telephone[j]); 
       node->followings[(int)telephone[j]-48] = &aux; 
     counter++; 

      } 
      node = node->followings[(int)telephone[j]-48]; 
     } 
    } 

    cout << counter << endl; 
} 

ノードnode->followings[(int)telephone[j]-48]->numberの数にアクセスしようとしたとき、私はセグメンテーションフォールトを取得しますが。誰もがなぜ私はそのエラーをgettintとそれを修正する方法を知っていますか?事前 に、私はあなたがfollowingのサイズを変更しているC++

+3

すべての警告とデバッグ情報(例えば[GCC](http://gcc.gnu.org/)を使用している場合は 'g ++ -Wall -Wextra -g')でコンパイルしてから**デバッガを使用する** (例えば 'gdb')とおそらく[valgrind](http://valgrind.org/)のようなものです。あなたのfix-my-codeの質問は話題にはなりません。 –

+1

'followings'はnullptrのベクトルなので、' - > number'はsegfaultsです。 – freakish

+0

'telephone [j] - '0''は移植可能ですが、 'telephone [j] -48'は移植性がありません。 – molbdnilo

答えて

2

に新しい少しだけど、それはコンポーネントのデフォルト値が含まれている

おかげで、それはnullptrある(ので、それらへのアクセスは、セグメンテーションフォルトれます)。おそらく、あなたはどこかfollowing->push_back(someptr)Node割り当てられをポイントしているsomptrとを使用する必要がありますfollowings.reserve(10);

followings.resize(10);を置き換える必要があります。

おそらくsmart pointers、おそらくstd::unique_ptrなどを使用します。すべての警告&デバッグ情報とfollowings

コンパイル中の成分の種類としてstd::unique_ptr<Node>次いでデバッガ(例えばgdb)とおそらくvalgrindを使用する(例えばg++ -Wall -Wextra -g ... GCCを使用している場合)。

関連する問題