gpt4 book ai didi

c - 修改通过引用传递的指针

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:13 24 4
gpt4 key购买 nike

我没有完全理解这个错误:第一次取消引用时,它具有正确的值 (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);

关于c - 修改通过引用传递的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27144338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com