简体   繁体   English

std::cout 在打印变量和函数表达式时表现不同

[英]std::cout behaves differently when printing variable vs function expression

I'm new to c++ and I'm facing an odd behavior from std::cout that I don't understand.我是 C++ 的新手,我面临着来自std::cout的奇怪行为,我不明白。 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.特别是,当我想打印第二个节点的值时,使用cout << nd.next[2]->next[17]->val ,我得到了一些复杂的字节。 However, if I set it to a variable first, eg string let2 = nd.next[2]->next[17]->val , then use cout << let2 , it prints the correct character.但是,如果我先将它设置为变量,例如string let2 = nd.next[2]->next[17]->val ,然后使用cout << let2 ,它会打印正确的字符。 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) (此外,由于我对 C++ 非常陌生,因此对我在代码中做错的任何其他评论表示赞赏)

#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;
}

Regarding the second part of your question ("what I am doing wrong"), in the insert() method you create Node() object on stack and assign next[curIdx] with a pointer to this object.关于您问题的第二部分(“我做错了什么”),在insert()方法中,您在堆栈上创建Node()对象并为next[curIdx]分配一个指向该对象的指针。 But that stack object is destroyed automatically once the execution steps out of the scope where that object is defined, so next[curIdx] ends up pointing to garbage (memory where the object used to be before destroying).但是,一旦执行超出定义该对象的范围,该堆栈对象就会自动销毁,因此next[curIdx]最终指向垃圾(对象在销毁之前曾经所在的内存)。
Not sure how the next line is even working, next[curIdx] points to garbage at this point: next[curIdx]->insert(str, idx+1);不知道下一行是如何工作的, next[curIdx]指向垃圾: next[curIdx]->insert(str, idx+1);

Instead you should allocate Node objects on heap with the new operator, ex:相反,您应该使用new运算符在堆上分配 Node 对象,例如:

        if (!next[curIdx]) {
            next[curIdx] = new Node();  // allocated on heap
            next[curIdx]->val = cur;
        }

but then you should make sure to deallocate ( delete ) them at some point to avoid memory leaks.但是你应该确保在某个时候释放( delete )它们以避免内存泄漏。 Destructor of Node may be a good place for that – you can recursively delete all non-null Nodes from next array.节点的析构函数可能是一个好地方——你可以递归地从下一个数组中delete所有非空节点。

Also you could use smart pointers instead of raw pointers, they automatically delete objects when they can't be no longer accessed (garbage collector does that automatically in other languages like Java and C#).您也可以使用智能指针而不是原始指针,它们会在无法再访问时自动删除对象(垃圾收集器在其他语言(如 Java 和 C#)中会自动执行此操作)。

More on stack vs heap: https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/有关堆栈与堆的更多信息: https : //www.geeksforgeeks.org/stack-vs-heap-memory-allocation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 std :: cout无法打印到控制台 - std::cout not printing to console 在Windows或Linux上运行时,功能的行为有所不同 - Function behaves differently when run on Windows or Linux std :: is_function的实现-为什么我的实现行为不同? - Implementation of std::is_function - why my implementation behaves differently? 为什么使用默认构造函数构造时的 std::string object 行为不同? - Why std::string object when constructed with default constructor behaves differently? Visual studio(std :: cout)不打印我的变量值 - Visual studio (std::cout) not printing my variable value 打印带有一个std :: cout和多个std :: cout的静态int的函数有什么区别? - What is the difference in printing a function with a static int with one std::cout and multiple std::cout? std :: ofstream在DLL中的行为不同 - std::ofstream behaves differently in DLL <iostream> std:cout函数内没有打印(FIXED:for for issue issue) - <iostream> std:cout within function not printing (FIXED:for loop issue) 打印 null 指针时,std::cout 可以打印“NULL”而不是 0 吗? - Can std::cout print “NULL” instead of 0 when printing a null pointer? C ++ - 在打印char *时指定std :: cout的最大字符数 - C++ - Specify maximum character for std::cout when printing char*
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM