所以我想传递一个指向函数的指针,并让该函数从该函数内部修改该指针。 我一般如何做到这一点?在这里?
修改
由于treeNode是一个指针结构,我想在nodePtr->vendorDataRef
函数内部取removeLeftMostNode(...)
并以某种方式将其返回到调用函数。我以为我可以通过参数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;
}
}
答案 0 :(得分:3)
我一般如何做到这一点?
要修改任何对象,无论是对象还是指向对象的指针,都可以传递对象的引用。
void foo(int& i)
{
// Assign to i. The change will be visible in the calling function.
i = 10;
}
void bar(int*& ptr)
{
// Assign to ptr dynamically allocated memory.
// The memory will be valid in the calling function.
ptr = new int[20];
}
int main()
{
int i;
int* ptr;
foo(i); // When the function returns, i will be 10
bar(ptr); // When the function returns ptr will point to an array of 10 ints
ptr[5] = 20; // OK since memory for ptr was allocated in bar.
...
// Deallocate memory to prevent memory leak.
delete [] ptr;
}