24

A pointer stores the memory address of another variable. & gives an address, * reads the value at an address (dereference).

p holds the address of x, so *p gives the value of x

p holds the address of x, so *p gives the value of x

C++ 8 lines
int x = 10;
int *p = &x;        // p stores the address of x
cout << p;          // address, e.g. 0x7ffe10
cout << *p;         // 10
*p = 20;            // changes x through the pointer
cout << x;          // 20

int *q = nullptr;   // points nowhere (always initialise pointers)
Pointer and array C++ 3 lines
int arr[] = {10, 20, 30};
int *p = arr;           // array name = address of first element
cout << *(p + 1);       // 20  (pointer arithmetic)

Q & A

  1. What is a null pointer?
    A pointer that points to nothing (nullptr). Dereferencing it crashes the program, so check before use.
  2. What is a dangling pointer?
    A pointer that still holds the address of memory that has already been freed or has gone out of scope.
  3. What is a void pointer?
    A generic pointer (void*) that can hold the address of any type, but must be cast before dereferencing.