I'm new to c++ and I'm facing an odd behavior from std::cout that I don't understand. In particular, when I want to print the value of the second node, using cout << nd.next[2]->next[17]->val, I get some convoluted bytes. However, if I set it to a variable first, e.g string let2 = nd.next[2]->next[17]->val, then use cout << let2, it prints the correct character. My code is below, I was implementing a trie. (Also since I am very new to c++ any other comments about what I am doing wrong in the code is appreciated)
#include <iostream>
#include <set>
#include <iterator>
#include <map>
#include <string>
#include <unordered_map>
using std::set;
using std::cout;
using std::endl;
using std::string;
struct Node {
    Node* next[26]; 
    string val; 
    void insert(string str) {
        cout << "insert " << str << endl;
        insert(str, 0);
    }
    void insert(string str, int idx) {
        if (idx >= str.length()) {
            return;
        }
        char cur = str[idx];
        int curIdx = cur - 'a';
        cout << "cur: " << cur << endl;
        cout << "cur idx: " << curIdx << endl;
        if (!next[curIdx]) {
            Node newNode = Node();
            newNode.val = cur;
            next[curIdx] = &newNode;
        }
        next[curIdx]->insert(str, idx+1);
    }
};
int plus(int a, int b) {
    return a+b;
}
int main() {
    Node nd = Node();
    nd.insert("cryptography");
    string let1 = nd.next[2]->val;
    string let2 = nd.next[2]->next[17]->val;
    cout << "first letter " << let1 << endl; // c
    cout << "second letter " << nd.next[2]->next[17]->val << endl; // wrong
    cout << "second letter " << let2 << endl; // work as expected
    cout << "sum " << plus(1,2) << endl; // work as expected
    // cout << nd.next[2]->next[17]->val << endl;
    return 0;
}
 
     
    