-1

I am just learning the concept of pointers in c++. From what I have studied I understand that & is used for finding memory address of a variable. I want to ask if there is also memory address of a pointer. Take a look at my code below

#include <iostream>

using namespace std;

int main() {

int fish=5;
int *fishpointer=&fish;

cout << fishpointer << endl;
cout << &fishpointer << endl;

return 0;
}

The above code on run print the following

0x7fff64cc1f14
0x7fff64cc1f18

Each time I run it the both the address changes, but the second address is I think 4 more in value than first. Why that is so? I understand that first address is of variable fish, but not able to understand about second address. Is it just garbage value?

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
Paras
  • 210
  • 3
  • 12
  • ' if there is also memory address of a pointer' - yes, there is. – Martin James Feb 07 '16 at 18:14
  • A pointer is just a variable whose value is an address. As such, `fishpointer` has an address - just like any other variable. So you can take its address with `&fishpointer`. – Fabio says Reinstate Monica Feb 07 '16 at 18:14
  • No it is not garbage. You correctly understood it to be the address of the pointer variable. – Weather Vane Feb 07 '16 at 18:14
  • 1
    "A pointer" can be used to colloquailly refer to a variable of pointer type, but technically it's a value, not a variable -- you can't take the address of a value, but you can take the address of a variable that contains a value. Splitting hairs, I know, but it's important to make the distinction when learning this stuff. – Cameron Feb 07 '16 at 18:18
  • @Cameron I refer to the value as an address, not a pointer. – Martin James Feb 07 '16 at 19:13

3 Answers3

1

&fishpointer Is the address of the pointer.

Look pointer to pointers:

http://www.tutorialspoint.com/cprogramming/c_pointer_to_pointer.htm
1

The second value is the address of the variable fishpointer.

The compiler has decided to put the two variables next to each other in memory, which is why their addresses are so similar. The language doesn't guarantee this will happen - and you may even see different behaviour if you turn on optimisation.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
1

A pointer is a value (the address in memory at which an object resides). But fishpointer is a variable (whose type happens to be one that contains a pointer value).

So you can take the address of fishpointer with &, and it gives you the address of the variable that contains the address of fish.

Since fish and fishpointer are two local variables, the compiler puts them both on the stack, and in this case they end up next to each other (the exact layout of variables in memory is implementation-dependent). On your platform, it seems that pointers are 4-bytes each -- hence the four byte difference in the addresses of the variables.

Cameron
  • 96,106
  • 25
  • 196
  • 225