Search code examples
structquadtree

Changing a struct value within a function with c++


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

Solution

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