我有一个看起来像这样的课程:
class myTreeNode
{
public:
char Data;
myTreeNode *childA = NULL; //A's always go in child1
myTreeNode *childT = NULL; //T's always go in child2
myTreeNode *childC = NULL; //c's always go in child3
myTreeNode *childG = NULL; //G's always go in child4
};
然而,当我去分配Data
一个值时,我收到一个seg错误。我这样做:
root->childT->Data = p_data;
其中p_data
是char = t
,而root
是由myTreeNode *root = new myTreeNode;
创建的指针。为什么在分配Data
值时会出现seg错误?它与执行char Data = 't'
只是一样吗?
答案 0 :(得分:4)
您的孩子没有指向任何记忆位置。您只为根节点创建了一个新实例。您正在获取段错误,因为您正在取消引用空指针。
例如:
class myTreeNode
{
public:
char Data;
myTreeNode *childA = NULL; //A's always go in child1
myTreeNode *childT = NULL; //T's always go in child2
myTreeNode *childC = NULL; //c's always go in child3
myTreeNode *childG = NULL; //G's always go in child4
};
int main()
{
// allocate memory
myTreeNode *root = new myTreeNode;
root->childT = new myTreeNode; // allocate child
root->childT->Data = 'a';
// delete allocated memory
delete root->childT;
delete root;
return 0;
}