Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ variables not changing with initial pointer variables

I don’t understand why the output of this code is not 1, 4, 90. Instead, it is always 1, 4, 83.

int main()
{
    float u = 83;
    vector<float> te = {1, 4, u};
    u = 90;
    cout << te[0] << " " << te[1] << " " << te[2] << "\n";
    return 0;
}

I tried adding a pointer, but this did not work:

int main()
{
    float u = 83;
    float *x = &u;
    vector<float> te = {1, 4, *x};
    u = 90;
    x = &u;
    cout << te[0] << " " << te[1] << " " << te[2] << "\n";
    return 0;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your first example, when you create the te vector with the u value, you are creating a vector containing a copy of the value.

When u is equal to 83, doing this:

vector<float> te = {1, 4, u};

creates a vector which includes a copy of the value 83. It is equivalent to doing:

vector<float> te = {1, 4, 83};.

In your second example, when you use the asterisk on a pointer, you are dereferencing that pointer. By dereferencing you are no longer referencing the memory location of u — you are accessing the value it currently holds.

When you dereference x in the creation of te, the te array creates a copy of the value that dereferencing x provides. At this point in the code, x points to u containing 83. So this:

vector<float> te = {1, 4, *x};

is equivalent to this again:

vector<float> te = {1, 4, 83};

What you would need to achieve what you want to achieve is a vector of pointers. This would provide you the result you are looking for:

int main()
{
    float u = 83;
    float v = 1;
    float w = 4;

    float *x = &u;
    float *y = &v;
    float *z = &w;

    vector<float*> te = {y, z, x};

    u = 90;
    x = &u;

    cout << *te[0] << " " << *te[1] << " " << *te[2] << "\n";
    return 0;
}

By holding a bunch of pointers in your vector, you can update the values that the pointers are pointing to, and then dereference the pointers held in your array. This would provide you with the current values held in the original u, v or w floats.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading