0
#include <iostream>
using namespace std;
#include <string>
#include <map>

typedef struct node{
    char a;
    map<char , node*> b;
}node;

node a[26] ; 

void add(string s){
    node *prev = &(a[s[0]-'a']);
    int i = 0;
    int len = s.length();
    for(i = 1; i < len; ++i){        
        map<char,node*>::iterator it = ((*prev).b).find(s[i]);
        if(it != ((*prev).b).end()){
            prev = it->second;
        }
        else{
            cout << (*prev).a << endl;
            node pt;
            pt.a = s[i];
            ((*prev).b)[s[i]] = &pt;
            prev = &pt;
        }
    }
}

int main(){
    string s = "helloworld";
    string t = "htllothis";
    int i = 0 ;
    for(i = 0;i < 26;++i){
        a[i].a = 'a'+i;
    }
    add(s);
    add(t);
    return 0;
}

I am trying to implement tire datastructure using map and char but cout<< (*prev).a is printing some other chars. What is the mistake I have done?

4
  • What is the expected output and what output do you get? Commented Jul 24, 2015 at 13:13
  • It has to print chars of "helloworl" and "tllothis" with newline for each char but instead it is printing some garbage values. Commented Jul 24, 2015 at 13:17
  • 1
    typedef struct node { ... } node; is very C like. In C++, you can just simply use struct node { ... }; as node is useable as is without a typedef. Commented Jul 24, 2015 at 13:44
  • 2
    @crashmstr that typedef struct crap drives me nuts, what a terrible solution. Commented Jul 24, 2015 at 13:48

2 Answers 2

4

First of all (*prev).b is equivalent to prev->b, I do not understand why you use -> for iterator but not for this pointer, it is difficult to read your code.

Main problem that you insert pointer to a local object into map:

       cout << (*prev).a << endl;
       node pt;
       pt.a = s[i];
       ((*prev).b)[s[i]] = &pt;
       prev = &pt;

After leaving this block that pointer becomes invalid and you get random errors. You either should create node by operator new and better have smart pointer in your map, or keep node by value.

Sign up to request clarification or add additional context in comments.

Comments

0
(...)
node pt;
pt.a = s[i];
((*prev).b)[s[i]] = &pt;
prev = &pt;
(...)

In your add function you're creating a local node and passing its address into an entry of the map and then make it the prev node. Once the variable is out of scope it is deleted and your prev node points to an invalid address. So next time you print prevanything could happen as it is Undefined Behaviour.

1 Comment

Yep, I thought the same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.