【发布时间】:2016-12-18 23:50:25
【问题描述】:
所以我想将一个指针传递给一个函数,并让该函数从该函数内部修改该指针。 一般情况下我该怎么做?在这里?
编辑:
由于 treeNode 是一个指针结构,我想在 removeLeftMostNode(...) 函数中获取 nodePtr->vendorDataRef 并以某种方式将其返回给调用函数。我以为我可以通过removeLeftMostNode(...) 的参数来做到这一点,因此removeLeftMostNode(...aVendor* vendorDataRef)
即
aBst::treeNode * aBst::removeNode(aBst::treeNode * nodePtr)
{
aVendor * tempVendorPtr; //<----...to be assigned to this
treeNode * nodeToConnectPtr, * tempPtr;
...
tempPtr = removeLeftMostNode(nodePtr->right, &tempVendorPtr);
...
}
aBst::treeNode * aBst::removeLeftMostNode(aBst::treeNode * nodePtr, aVendor* vendorDataRef)
{
if(nodePtr->left == NULL)
{
//Target acquired, modify the value of vendorData through parameter
vendorDataRef = nodePtr->vendorData; //<---I want this pointer...
return removeNode(nodePtr);
}
else
return removeLeftMostNode(nodePtr->left, vendorData);
}
这是 treeNode 结构
struct treeNode
{
aVendor * vendorData;
treeNode * left;
treeNode * right;
};
正如您可能猜到的,这是从二叉搜索树中删除条目的代码的一部分。这是间接调用它的代码。
bool aBst::remove(char nameOfVendor[])
{
bool failControl = false;
removeValue(root, nameOfVendor, failControl);
return failControl;
}
aBst::treeNode * aBst::removeValue(aBst::treeNode * subTreePtr, char nameOfVendor[], bool& success)
{
//Note: the subTreePtr should be root in initial call
treeNode * tmpPtr;
char name[MAX_CHAR_LENGTH];
subTreePtr->vendorData->getName(name);
if(subTreePtr == NULL) //Empty Tree
{
success = false;
return NULL;
}
else if(strcmp(name, nameOfVendor) == 0) //Evaluates to true if there is a match
{
//Item is in root of subTreePtr
subTreePtr = removeNode(subTreePtr);
success = true;
return subTreePtr;
}
else if(strcmp(name, nameOfVendor) < 0) // Go left
{
tmpPtr = removeValue(subTreePtr->left, nameOfVendor, success);
subTreePtr->left = tmpPtr;
return subTreePtr;
}
else // Go Right
{
tmpPtr = removeValue(subTreePtr->right, nameOfVendor, success);
subTreePtr->right = tmpPtr;
return subTreePtr;
}
}
【问题讨论】:
-
“我要避免按值传递”,几乎每个参数(
success除外)都是按值传递的。 “如果我使用指向指针的指针,我担心它不会修改removeNode中的tempVendorPtr的值”你怕什么,它会修改指针。你能澄清一下吗? -
抱歉,到底是什么问题?或者你在哪里尝试实现“将指针传递给函数并让该函数修改该指针”
-
参考接收。相当琐碎。
标签: c++ pointers reference binary-search-tree