[英]Modifying a pointer passed by reference
我沒有完全理解此錯誤:第一次取消引用時,它具有正確的值(0)。 但是,在第二次迭代時,變量的地址被設置為隨機地址(不是隨機的,它只是將3加到指針的當前地址,而不是加到指針的值)。
void constructTree(const unsigned int data[], const unsigned int dataSize, unsigned int *dataPointer, node* currentNode)
{
//If the pointer is out of bounds, the tree has been built
if (*dataPointer > dataSize) return;
//If the dataPointer is pointing to the id of the current node
if (data[*dataPointer] == currentNode->m_id)
{
printf("%d, ", currentNode->m_id);
//Create the left and right nodes
if (data[*dataPointer + 1] != 0) {
currentNode->m_left = (node*)malloc(sizeof(node));
currentNode->m_left->m_id = data[*dataPointer + 1];
currentNode->m_left->m_left = NULL;
currentNode->m_left->m_right = NULL;
currentNode->m_left->m_parent = NULL;
}
if (data[*dataPointer + 2] != 0) {
currentNode->m_right = (node*)malloc(sizeof(node));
currentNode->m_right->m_id = data[*dataPointer + 2];
currentNode->m_right->m_left = NULL;
currentNode->m_right->m_right = NULL;
currentNode->m_right->m_parent = NULL;
}
printf("%d", *dataPointer);
constructTree(data, dataSize, &*dataPointer + 3, currentNode->m_left);
constructTree(data, dataSize, &*dataPointer + 3, currentNode->m_right);
}
}
調用此函數:
unsigned int dataPointer = 0;
constructTree(vector, vectorSize, &dataPointer, head);
我假設您不想更改原始值,因此請使用一個臨時變量:
int datatemp = *dataPointer + 3 ;
constructTree(data, dataSize, &datatemp , currentNode->m_left);
constructTree(data, dataSize, &datatemp , currentNode->m_right);
如果確實要更改它,請先更改它,然后再傳遞指針:
*dataPointer = *dataPointer + 3 ;
constructTree(data, dataSize, dataPointer , currentNode->m_left);
constructTree(data, dataSize, dataPointer , currentNode->m_right);
您實際上有兩個問題:第一個是由於運算符的優先級 。 地址( &
)和取消引用( *
)運算符都比加法運算符具有更高的優先級,因此&*dataPointer + 3
與(&*dataPointer) + 3
,並且地址和取消引用運算符取消彼此的dataPointer + 3
與dataPointer + 3
相同。
第二個問題是您不能使用表達式的地址,必須將表達式存儲在一個臨時變量中並將該地址傳遞給該變量。 或者,如果您想修改原始值,請執行此操作並傳遞指針。
所以要么
int temp = *dataPointer + 3;
constructTree(data, dataSize, &temp, currentNode->m_left);
constructTree(data, dataSize, &temp, currentNode->m_right);
要么
*dataPointer += 3;
constructTree(data, dataSize, dataPointer , currentNode->m_left);
constructTree(data, dataSize, dataPointer , currentNode->m_right);
C實際上不支持引用傳遞,也許您只是混用了術語? 我認為問題出在您的電話上:
constructTree(data, dataSize, &*dataPointer + 3, currentNode->m_right)
如果我理解您的想法,則希望它傳遞dataPointer加3所指向的值的地址。實際上,它正在傳遞的是已取消引用的指針的地址,即指針(dataPointer)+ 3。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.