Address Operator

  • & is the address operator
  • &x is the address of the variable x in memory (+1 represents +1 byte)

Pointer Variable

  • A variable that contains the address of another variable is calla pointer
  • Declaring: int *x_ptr; declares a pointer called x_ptr that can point to an int variable
    • x_ptr = &x; assigns the address of x to x_ptr, so x_ptr now points to x
    • Pointers can be initialised during declaration: int *x_ptr = &x;
  • Reading: To access the value of the variable that a pointer is pointing to, the dereferencing or indirection operator, *, is used
    • *x_ptr is the value of x
  • Writing: the dereferencing operator can also be used to write the value of the variable that a pointer is pointing to
    • *x_ptr = 123; will set the value of x to be 123
  • Incrementing: x_ptr++ will increment the address stored in the pointer by the size of the datatype that it is pointing to (in bytes)
    • int: 4 bytes, float: 4 bytes, char: 1 byte, double: 8 bytes
    • This extends to incrementing by more than 1: x_ptr += 3 will increment x_ptr by 3 times the size of the datatype it is pointing to (e.g. if it is an int, x_ptr will be incremented by 12 bytes)

Why Pointer

  • To allow a function to modify the value of a variable (by passing a pointer to the variable into the function)
  • To pass the address of the first element of an array to a function so that it can access all the elements in the array