如何通过参数修改指针

How to modify a pointer through a parameter

本文关键字:指针 修改 参数 何通过      更新时间:2023-10-16

我想传递一个指针给一个函数让那个函数在函数内部修改那个指针。我一般怎么做?在这里吗?

编辑:

由于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;
            }
}

我一般怎么做?

要修改任何对象,无论是对象还是指向对象的指针,都可以传递对它的引用。

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;
}