修改引用传递的指针

时间:2014-11-26 08:26:58

标签: c pointers

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

3 个答案:

答案 0 :(得分:2)

我假设您不想更改原始值,因此请使用临时变量:

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

答案 1 :(得分:0)

你实际上有两个问题:第一个是因为operator precedence。地址(&)和解除引用(*)运算符的优先级都高于加法运算符,因此&*dataPointer + 3(&*dataPointer) + 3相同,并且作为地址-of和dereference运算符互相取消,与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);

答案 2 :(得分:0)

C实际上并不支持通过引用传递,也许你刚刚将条款混淆了? 我认为问题出在你的行中:

constructTree(data, dataSize, &*dataPointer + 3, currentNode->m_right)

如果我理解你正在思考,那么你期望这会传递dataPointer所解决的值的地址加上3.实际上它正在做的是传递解除引用指针的地址,这是指针(dataPointer)+ 3。

  • dataPointer = pointer
  • * dataPointer = dataPointer寻址的值
  • & * dataPointer = dataPointer寻址的值的地址