0

我想在 C++ 中创建一个快速四叉树,但发现当我在函数中更改结构的值时,值会恢复。同样在递归函数中,我不会创建一些全局数据。我该怎么做呢?

#include <iostream>

struct a{
    unsigned int value;
    struct a * leaf[4];
};

void build(struct a root, unsigned int depth){

    depth++;

    root.value = 0;

    struct a leaf0;
    root.leaf[0] = &leaf0;
    struct a leaf1;
    root.leaf[1] = &leaf1;
    struct a leaf2;
    root.leaf[2] = &leaf2;
    struct a leaf3;
    root.leaf[3] = &leaf3;

    if (depth != 5) {
        build(*root.leaf[0], depth);
        build(*root.leaf[1], depth);
        build(*root.leaf[2], depth);
        build(*root.leaf[3], depth);
    }
}

int main(int argc, const char * argv[])
{
    struct a root;

    root.value = 364;

    build(root, 0);

    std::cout << root.value;
    return 0;
}
4

1 回答 1

0

您必须将结构的地址传递给您的函数(它应该接受指向该结构的指针):

void build(struct a *root, unsigned int depth) {  
  ...
}

int main(int argc, const char * argv[])    
  ...
  build(&root, 0);
}
于 2012-10-25T01:05:48.893 回答