0
struct node {
    int data;
    node* next;
};

int main()
{
    int* p = nullptr;
    std::cout << p << std::endl;

    node* nu = new node;
    std::cout << *&nu << std::endl;
}

The question: is nu a memory address, are pointers really just memory address or is there something that I am missing here. What significance does *nu have, is this the object contained in the address, &nu gives me the memory address itself. if nu had been an integer it would have given me a number?. Would appreciate the help.

MLavoie
  • 9,671
  • 41
  • 36
  • 56
M33ps
  • 31
  • 3
  • 2
    This should be covered in any introductory text. Perhaps try one of these [books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – cigien Aug 06 '20 at 23:31
  • `*&nu` is the same as just `nu`. You are taking the address of `nu` itself (not the address of the `node` that it holds), and are then dereferencing that to get back to `nu` itself. So `std::cout << *&nu` and `std::cout << nu` output the same thing. – Remy Lebeau Aug 07 '20 at 00:08

2 Answers2

0

&nu uses the address-of operator to get the address of the pointer, resulting in a pointer to the pointer. The * indirection operator then gets the contents of the new pointer, which is the value of the original pointer nu and is what you're sending to cout.

jkb
  • 2,376
  • 1
  • 9
  • 12
0

is nu a memory address, are pointers really just memory address or is there something that I am missing here.

nu is a pointer to a node and it means that nu "points to" a memory location (in this case on the heap) where the node has been constructed. The memory location is the address and so yes nu is essentially a memory address. If you print it, you would get a hex value - the address itself.

What significance does *nu have, is this the object contained in the address

Syntax such as *nu (or generally *pointer) translates to reaching to where the pointer points. The *, which is called dereference operator, is used in C++ to get the value behind the pointer.

&nu gives me the the memory address itself.

The & is the way to acquire the address of a variable. Writing &nu means that you want to get the address of the nu variable. Note that it is not the address of the node but the nu variable itself. This variable lives in the memory too (on the stack) and so has the address.

if nu had been an integer it would have given me a number?

No, you would get the address as well. & gives you the address of the variable, not the value. It might feel tricky with a pointer because the value of the pointer is the address.

*&nu

In this case you've acquired the address of nu variable (&n) and immediately reached for the value behind it (*&nu). It is equivalent of just nu because the value is the address of the node somewhere on the heap.

Dharman
  • 30,962
  • 25
  • 85
  • 135