samedi 4 mars 2023

c++: segmentation fault for Trie data structure [closed]

I am a noobie to c++ and I'm recently learning trie data structure. As I was implementing the header file for the Trie, I've encountered segmentation fault that I cannot resolve. I used the typical print out method to find the location of the error and it turns out that this line

temp->isEmpty = true;

is problematic and I don't know what's wrong with it. Here's my header file code, can somebody please take a look and help me out?

#ifndef _TRIE_HPP_
#define _TRIE_HPP_
#include <iostream>
using namespace std;

class Node{
public:
    Node* children[26];
    bool isEmpty;
    string val;
    Node(){
        this->isEmpty = false;
        this->val = "";
        for(int i = 0; i<26; i++){
            Node* temp = this;
            temp = children[i];
            temp->isEmpty = true; // this line causes segmentation fault
        }
    }
    ~Node();
};
#endif

int main(){
    string input;
    Node* myTrie = new Node(); // this line causes segmentation fault

    cin >> input;
    myTrie->insert(input);
}

I've also tried temp->children[i]->isEmpty = true; but that also throws segmentation fault

Aucun commentaire:

Enregistrer un commentaire