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

Pointers explanation in C++

I am self learning C++ and I found my self on the Pointers section of C++.

To my understanding the pointer allocates the value of a variable to a memory.

But I came across on this problem which the answer is 588.

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

And I cannot figure out how this number came up.

Can someone please explain me step by step how 588 came up ?

Thanks in advance.


#include <iostream>

int main() {
    int *p, *q, *t;

    // Allocate memory and initialize pointers and values
    p = new int;
    q = new int;
    t = new int;
    *p = 17;
    *q = 7;
    *t = 42;

    p = t; // Make pointer p point to the same location as pointer t
    t = q; // Make pointer t point to the same location as pointer q

    *t = *p * *q;

    *q = *q + *t;

    std::cout << *t << std::endl;


    return 0;
}

>Solution :

You can easily get what is going on if you output all three pointers and theirs values after each change to them, or by using a debugger. This is what happens:

*p = 17;
*q = 7;
*t = 42;

// p points to an int with value 17
// q points to an int with value 7
// t points to an int with value 42

p = t; // Make pointer p point to the same location as pointer t

// p points to an int with value 42 (the same as t)
// q points to an int with value 7
// t points to an int with value 42 (the same as p)
    
t = q; // Make pointer t point to the same location as pointer q

// p points to an int with value 42 (now different than t)
// q points to an int with value 7 (the same as t)
// t points to an int with value 7 (the same as q)

*t = *p * *q;   // *t = (*p) * (*q) = 42 * 7 = 294

// p points to an int with value 42
// q points to an int with value 294 (still the same as t)
// t points to an int with value 294 (still the same as q)

*q = *q + *t;   // *q = (*q) + (*t) = 294 + 294 = 588

// p points to an int with value 42
// q points to an int with value 588 (still the same as t)
// t points to an int with value 588 (still the same as q)

std::cout << *t << std::endl;   // prints 588 (the same as q)

However note that something like p = t overwrites the address p was pointing to, therefore you cant free up the allocated memory anymore.

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