我有以下代码片段:
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/