2017-07-18 109 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错误,以及如何解决它?

感谢您提前 我有点新的C++

+3

编译所有警告和调试信息(例如'g ++ -Wall -Wextra -g'如果使用[GCC](http://gcc.gnu.org/)...)然后**使用调试器** (例如'gdb')或许[valgrind](http://valgrind.org/)。你的修复我的代码问题是脱离主题。 –

+1

因为'followings'是nullptrs的一个向量,所以''> number' segfaults。 – freakish

+0

'电话[j] - '0'是便携式的,但'电话[j] -48'不是。 – molbdnilo

回答

2

所调整following但随后它包含组件的默认值,即nullptr(所以给他们的任何访问段错误)。你或许应该用followings.reserve(10);

更换followings.resize(10);你应该使用的地方following->push_back(someptr)somptr是一个以点带分配Node

您可能应该使用smart pointers,或许是std::unique_ptrstd::unique_ptr<Node>作为成分的followings

编译所有警告&调试信息的类型(例如g++ -Wall -Wextra -g如果使用GCC ...),那么使用调试器(例如gdb),也许valgrind