-4

I am a noobie in C++ and its pointers, and I don't understand why in this code it is showing different addresses. I am also having trouble to understand if pointers can hold values or only addresses.

int* y;
std::cout << "y address is: " << y << std::endl;
std::cout << "y address is: " << &y << std::endl;

Output:

y address is: 0x41c33e
y address is: 0x28fefc
  • 3
    `&` gets the address of its operand. That's all you need to know (assuming you know what a pointer is.) – juanchopanza May 18 '16 at 09:06
  • Before understanding pointers, you need to understand _type, object and value`. Example `int a = 7` defines the _object_ `a`, with _type_ `int`, and initial value `7`. – MSalters May 18 '16 at 09:34

4 Answers4

3

The value of a pointer can be the address of a different object. You get two different addresses printed because the pointer itself is also stored at some memory address:

int* y;    // y is pointing to some address (where there is not yet a int!)

std::cout << "y address is: " << y << std::endl;  // this is the adress 
                                                  // the pointer is pointing to
std::cout << "y address is: " << &y << std::endl; // this is the memory
                                                  // address where the
                                                  // pointer is stored
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
2

What is a pointer?

Pointer is a variable that contains the address of another variable.

Here you take the address pointed to by the pointer:

std::cout << "y address is: " << y << std::endl; 

As the pointer have his own address, here you take address of this pointer:

std::cout << "y address is: " << &y << std::endl;

That's why are two different addresses.

Sergiy Shvets
  • 180
  • 2
  • 14
2

I think you are getting confused with what pointers actually are.

int y;
int* y_pointer = &y;

In the above, y holds an integer, and y_pointer holds the memory address that y resides in (note the & meaning address of). Pointers can only hold memory addresses (as they are pointers to memory elements), but this doesn't mean you can't access the variable they point to.

Dereferencing pointers using the * character can be used to do this. There is a good question here about doing that for further reading.

Community
  • 1
  • 1
Scott Stainton
  • 394
  • 2
  • 14
1
//to understand it better lets do
int x;
int* y=&x;

The type of the variable y is int* which is an integer pointer.

y gives the memory address value that is stored in the integer pointer, which would be the memory location where x is stored.

&y is the address of the variable y itself, i.e the memory location where the pointer is stored.

Biruk Abebe
  • 2,235
  • 1
  • 13
  • 24