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

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

最佳答案

我假设你不想改变原始值,所以使用一个临时变量:

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/

相关文章:

c - 两次调用 mmap 时出现 SIGSEGV

c - C 中的函数和数组

c++ - 在C++代码的编译器中出现错误,详细内容在

c - 将struct的成员声明为c中的指针并使用它

c - 将 int arg 转换为 double 的 Gcc 编译器选项?

c - 为什么全局指针不能重新指向另一个对象,而局部指针可以?

c - 如何扫描文本文件的字数和字数?

c - GetSaveFileName()如何更新 "File name:"控件中的文件扩展名?

C - 处理共享内存时出现段错误

pointers - Rust 中的托管指针与无限生命周期的借用指针有何不同?