简体   繁体   中英

Is initialized struct immutable?

I initialized a test case as a global variable, here:

void InsertNode(BSTNode* &t, const int &key) {
    if (t == NULL) {
        t = new BSTNode;
        t->key = key;
        t->left = t->right = NULL;
    } else {
        if (key != t->key) {
        if (key < t->key)
                InsertNode(t->left, key);
            else
                InsertNode(t->right, key);
        }
    }
}

BSTNode t1[] = {
 {4, &t1[1], &t1[2]},
 {2, &t1[3], &t1[4]},
 {6, &t1[5], &t1[6]},
 {1, NULL, NULL},
 {3, NULL, NULL},
 {5, NULL, NULL},
 {7, NULL, NULL}
};

int main() {
    InsertNode(t1, 0);
    return 0;
}

However, when I try to modify t1, it gives me an error:

invalid initialization of non-const reference of type 'BSTNode*&' from a temporary of type 'BSTNode*'

Could someone explain this for me? Thank you!!

The problem is that your function is stating that it may change the pointer:

void InsertNode(BSTNode* &t, const int &key) {

it is taking a reference to a non-const pointer as a parameter, so it has the potential of modifying that pointer. However when you do this call:

InsertNode(t1, 0);

you are passing in a non-modifiable pointer, since t1 is an array. An array can be used like a pointer, but you can't make that pointer point somewhere else.

One way to deal with this would be to have two different functions:

void InsertNode(BSTNode* &t, const int &key);

void AddNode(BSTNode* t, const int &key) {
    assert(t!=NULL);
    if (key != t->key) {
    if (key < t->key)
            InsertNode(t->left, key);
        else
            InsertNode(t->right, key);
    }
}

void InsertNode(BSTNode* &t, const int &key) {
    if (t == NULL) {
        t = new BSTNode;
        t->key = key;
        t->left = t->right = NULL;
    } else {
        AddNode(t,key);
    }
}

And then call

AddNode(t1, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM