如何通过参数修改指针
How to modify a pointer through a parameter
我想传递一个指针给一个函数让那个函数在函数内部修改那个指针。我一般怎么做?在这里吗?
编辑:由于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;
}
相关文章:
- 修改函数中的指针(将另一个指针作为参数传递)
- 使用指针算法修改函数中的 2D 数组
- 结构对象的指针成员在传递给函数时被修改
- C:试图将指针值复制到另一个指针中,得到可修改的左值错误
- 如何在单个链表中交换两个节点的位置,只修改指针
- 为什么我可以通过原始指针而不是shared_ptr来修改对象
- 当原始数据是常量时,修改指针指向的位置是 UB 吗?
- 将指向矢量的指针推回,然后修改其值会影响推送的值.我应该怎么做?
- 如果指针在C++为 NULL 则修改指针
- 修改跨 fork() 的指针中的数据
- 当我修改、更改和“删除”原始指针时,是否需要指针副本
- 通过指针修改子函数中函数的局部变量的内容
- 使用指针修改 C++ 初学者---字符串
- 通过这样的常量指针修改非常量指针是合法的
- 通过指向引用的指针修改类变量
- 使用指针修改内容
- 使用指针修改向量
- 通过构造过程中获得的指针修改const对象
- 用指针修改字节
- 通过常量指针修改使用 new 创建的对象是否合法