我正在尝试编写一个程序来玩“Pangolin”(例如 this guy - 它会询问是/否问题,沿着二叉树走下去,直到到达叶节点。然后它“猜测”,如果用户说答案是错误的,询问用户他们在想什么,并提出一个将其与错误猜测区分开来的问题。然后将新数据添加到树中)。
这是我的树节点结构。对于包含问题的节点,NodeType 是 QUESTION_NODE;对于包含“对象”的节点,NodeType 是 OBJECT_NODE - 这是程序推断用户正在思考的事物。问题节点具有指向子节点的指针 - 一个表示是,一个表示否。
typedef struct _TreeNode {
NodeType type;
union {
char* question;
char* objectName;
} nodeString;
//children for yes and no answers: will be invalid when type is OBJECT_NODE
struct _TreeNode* yes;
struct _TreeNode* no;
} TreeNode;
由于这是一个学习练习,我尝试使用双指针来完成它。这是应该向树添加问题节点的函数:
void addData(TreeNode** replace, char* wrongGuess) {
//create a new object node for what the user was thinking of
// ... (code to get user input and build the new object node struct) ... //
//create a new question node so we don't suck at pangolin so much
// ... (code to get a question from the user and put it in a question node struct) ... //
//link the question node up to its yes and no
printf("What is the answer for %s?\n", newObjectName);
if (userSaysYes()) {
newQuestionNodePtr->yes = newObjectNodePtr;
newQuestionNodePtr->no = *replace;
}
else {
newQuestionNodePtr->no = newObjectNodePtr;
newQuestionNodePtr->yes = *replace;
}
//redirect the arc that brought us to lose to the new question
*replace = newQuestionNodePtr;
}
然后调用 addData 函数因此:
void ask(node) {
//(... ask the question contained by "node" ...)//
//get a pointer to the pointer that points to the yes/no member pointer
TreeNode** answerP2p;
answerP2p = userSaysYes() ? &(node.yes) : &(node.no);
//(... the user reports that the answer we guessed was wrong ...)//
puts("I am defeated!");
//if wrong, pass the pointer to pointer
addData(answerP2p, answerNode.nodeString.objectName);
我的(可能是错误的)理解是这样的:
在“ask()”中,我向 addData 传递一个指向“node”的成员“yes”(或 no)的指针。该成员又是一个指针。当我在 addData 中分配给“*replace”时,这应该修改结构,重定向其"is"(或否)成员指针以指向我创建的新问题节点。
我调试了一下,发现newQuestionNode和newObjectNode创建成功。 newQuestionNode 的子节点已正确分配。然而,新的问题节点没有插入到树中。 “*replace = newQuestionNodePtr”行没有达到我预期的效果,并且“ask”范围中“node”引用的节点没有重定向其子指针。
谁能看出我的理解有什么问题吗?或者也许是我在代码中没有正确表达它的方式?抱歉这个问题太长了。
最佳答案
您不应将传递给函数的指针声明为双指针。相反,将单个指针的地址传递给函数:
TreeNode* answerP2p;
answerP2p = userSaysYes() ? node.yes : node.no;
addData(&answerP2p, answerNode.nodeString.objectName);
关于c - 双指针: pointer to struct member that is a pointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13743306/