+ 1

How do you know the pointer address?

In some of the challenge questions, there are pointer addresses *p=&x. How can you work out the answer? Let me find an example!

22nd Jul 2017, 8:50 AM
Richard Appleton
Richard Appleton - avatar
4 Answers
+ 4
Hi! Don't confuse the two occurences of "*p" to be the same thing. The line int *p = &x; says: Declare a variable p of type (int *), that is, a pointer to an int, and assign to it the address of x. You could actually write this line like so: int* p = &x; (space between * and p), which I think is clearer, but equivalent: p is of type pointer to an int, and it gets the value 'address of x' Now, in the other line, cout << *p; *p means a different thing: the * operator (er.. I think it's called the dereferencing operator or some such) is applied to p, and it returns the contents of the memory location that p is pointing to. In other words: p contains the address of our int x, and *p here means the contents of that memory address. If you wanted to see the contents of the pointer p itself (the address of x), you could write cout << p; and get some funny-looking thing like 0x7fff1dd8b88c (the hex addr of x). Hope this helps! Wait I hope I didn't misunderstand the question :-)
23rd Jul 2017, 11:43 AM
Karbz P
Karbz P - avatar
+ 9
*p refers to the value pointed by pointer p which stores the address of x. This means that pointer p is pointing to x. The final output should be the value of x. x *= x + 9; // x becomes 190. cout << *p; // prints 190
22nd Jul 2017, 11:49 AM
Hatsy Rei
Hatsy Rei - avatar
0
int x = 10; int *p = &×; x* = x+9; cout << *p;
22nd Jul 2017, 8:55 AM
Richard Appleton
Richard Appleton - avatar
0
ok. I have clearly misunderstood something about pointers here! Does &x not give the address of x, rather than the value?
22nd Jul 2017, 2:54 PM
Richard Appleton
Richard Appleton - avatar