Pointers

Help Sessions

Check timetable!

Revision sessions reminder

Pointers

Memory

  • All data (variables) are stored in memory
  • You can think of memory as a big grid
  • Each segment of this grid has a unique identifier

Visualising memory with addresses

So far, we have only dealt with values

  • We can also access the address
  • By storing that address in a variable, we have a pointer

Pointer Syntax

To declare a pointer

<type> *<name_of_variable>

^ The * means don't request the storage to store <type>, but requests memory to store a memory address of <type>

Syntax example:

int *pointer

struct student *student

Visualise pointer declaration

Address of operator &

  • What if we want to query what the address of a variable is?
  • We can use the address_of operator:

&

Syntax of address of: &<variable>

Example

Dereferencing

  • Dereferencing is simply accessing the value at the address of a pointer
  • It uses the * symbol again (which causes confusion)
  • *my_int_pointer -> will get the integer at the address location

Three components to pointers in code

Common mistakes

  1. number_ptr = number;
  2. *number_ptr = &number;

Syntax cheat sheet

  • Declare a pointer: int *int_pointer;
  • Address of: &my_variable;
  • Dereference (Get the value at a pointer): *int_pointer;

Demo

Goals:

  • Create a variable
  • Get the address of that variable
  • Create a pointer variable
    • Use it!

But JAKE, why are they USEFUL

  • Let's look at an example with pointers and parameters

How can we edit a variable within a function?

Pass by reference*

  • Technically pass-reference-by-value but it's fine!

In the previous example, by passing the memory address, we can change the value in place and main will point to the updated value!

pointers and arrays 🤯

^ does data in main contain the doubled values?

How?

Arrays decay to pointers

  • Arrays point to the memory location which contains the first element
  • As arrays are contiguous, we can then move through the memory sequentially to find the next values
  • Very cool!

Feedback