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.
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;
}
3
Answers
There is written in the comments of the program
That is after these statements
*p
is equal to42
and*t
is equal to7
the same way as*q
is equal to7
because now the both pointerst
andq
point to the same memory.As a result you have that this statement
is euivalent to
That is the object pointed to by the pointers
t
andq
now contains294
.This statement
that is the same as
because the both pointers
t
andq
point to the same object and also is the same asor
So
294
plust294
yelds588
.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:
However note that something like
p = t
overwrites the addressp
was pointing to, therefore you cant free up the allocated memory anymore.When in doubt, you should draw it out! For example…
You are declaring 3 pointers that don’t point anywhere yet, thus:
You are allocating 3 integers (with indeterminate initial values), and making the 3 pointers point at them, thus:
You are dereferencing the pointers and setting the values of the integers they are pointing at, thus:
You are making
p
point at the same integer thatt
is pointing at, thus:You are making
t
point at the same integer thatq
is pointing at, thus:You are multiplying the values of the integers that
p
andq
are pointing at (42 * 7), and assigning the result (294) to the integer thatt
is pointing at, thus:You are adding the value of the integer that
q
andt
are both pointing at (294 + 294), and assigning the result (588) to the integer thatq
is pointing at, thus:You are printing out the value of the integer that
t
is pointing at, thus: