c++ - 结构和指针的成员,C++

标签 c++ pointers struct

我有以下代码片段:

struct Node
{
    Node* left;
    Node* right;
    string data;
};    

void test()
    {
        Node thing;
        thing.data = "h";
        thing.left = NULL;
        thing.right = NULL;

        cout<< "Thing data = " << thing.data << endl;

        Node* thing2;
        thing2->data = "f";
        thing2->left = NULL;
        thing2->right = NULL;

        cout<< "Thing2 data = " << thing2->data << endl;

    }

我遇到的问题是 thing2->data = "f"在运行时产生了段错误。我已经通过 GDB 运行该程序并收到此错误,但我无法弄清楚它的含义:

Reading symbols for shared libraries ++. done Thing data = h

Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: 13 at address: 0x0000000000000000 0x00007fff874d59a3 in std::string::assign ()

任何帮助都会很棒。谢谢!

最佳答案

thing2 是一个未初始化的指针。 它没有指向有效的 Node 对象。

你应该分配它:

thing2 = new Node;

或者让它指向一个有效的节点对象:

thing2 = & thing;

关于c++ - 结构和指针的成员,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4111433/

相关文章:

c - fprintf 在 C 中的使用

go - 如何在 switch 语句中先声明结构然后再初始化它?

c++ - 访问全局数据结构

c++ - OpenCV:将 Mat 转换为 UChar4

c# - 无法获取结构 C# 的指针

c++ - 使用自由函数作为 LPOVELAPPED_COMPLETION_ROUTINE

c - 如何用scanf()读取一句char指针?

将字符串复制到字符串数组中

c++ - 有 C++ 惰性指针吗?

arrays - 如何更改数组中结构的值?