使用c ++更改函数内的结构值

时间:2012-10-25 01:01:19

标签: struct quadtree

我想在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;
}

1 个答案:

答案 0 :(得分:0)

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

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

int main(int argc, const char * argv[])    
  ...
  build(&root, 0);
}