0

I wanted to create a quick quadtree in c++ but found that when I change a value of a struct within a function the value reverts. Also within the recursive function I wont some of the data created to be global. How do I do this?

#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;
}
josh247
  • 155
  • 1
  • 13
  • 1
    Lookup pass by value and pass by reference - you are passing by value, to make the change "stick" you should pass by reference. – John3136 Oct 25 '12 at 01:04

1 Answers1

0

You must pass the address of the struct to your function (which should accept a pointer to the struct):

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

int main(int argc, const char * argv[])    
  ...
  build(&root, 0);
}
Peter Gluck
  • 8,168
  • 1
  • 38
  • 37