Search code examples
c++pointersmemory-addressdereference

What exactly is the purpose of the (asterisk) in pointers?


I'm new to programming and I'm trying to wrap my head around the idea of 'pointers'.


int main()
{
    int x = 5;
    int *pointerToInteger = & x;
    cout<<pointerToInteger;

}

Why is it that when I cout << pointerToInteger; the output is a hexdecimal value, BUT when I use cout << *pointerToInteger; the output is 5 ( x=5).


Solution

  • * has different meaning depending on the context.

    1. Declaration of a pointer

      int* ap;  // It defines ap to be a pointer to an int.
      
      void foo(int* p); // Declares function foo.
                        // foo expects a pointer to an int as an argument.
      
    2. Dereference a pointer in an expression.

      int i = 0;
      int* ap = &i;   // ap points to i
      *ap = 10;       // Indirectly sets the value of i to 10
      
    3. A multiplication operator.

      int i = 10*20; // Needs no explanation.