Dereferencing a pointer reads or writes the object at the stored address.

dereference `*ptr` means the object pointed to by `ptr`.
write through pointer Assigning to `*ptr` updates the original variable.

Dereference

value
dereference.c
Replay: real traced execution (multi-file project)
#include <stdio.h>

int main(void) {
    int value = 3;
    int *ptr = &value;

    *ptr = *ptr + 2;

    printf("value=%d\n", value);
    return 0;
}
#include <stdio.h>

int main(void) {
    int value = 8;
    int *ptr = &value;

    *ptr = *ptr + 2;

    printf("value=%d\n", value);
    return 0;
}
#include <stdio.h>

int main(void) {
    int value = 10;
    int *ptr = &value;

    *ptr = *ptr + 2;

    printf("value=%d\n", value);
    return 0;
}
  1. value ← 3, ptr ← ⟨addr A⟩

    3int main(void) {4    int value→ 3 = 3; //@value=8, 105    int *ptr→ ⟨addr A⟩ = &value3;67    *ptr⟨addr A⟩ = *ptr + 2;89    printf("value=%d\n", value5);10    return 0;11}
    outputvalue=5
  1. value ← 8, ptr ← ⟨addr A⟩

    3int main(void) {4    int value→ 8 = 8;5    int *ptr→ ⟨addr A⟩ = &value8;67    *ptr⟨addr A⟩ = *ptr + 2;89    printf("value=%d\n", value10);10    return 0;11}
    outputvalue=10
  1. value ← 10, ptr ← ⟨addr A⟩

    3int main(void) {4    int value→ 10 = 10;5    int *ptr→ ⟨addr A⟩ = &value10;67    *ptr⟨addr A⟩ = *ptr + 2;89    printf("value=%d\n", value12);10    return 0;11}
    outputvalue=12

Follow the Pointer

  1. ptr stores the address of an existing variable.
  2. *ptr reads the value at that address.
  3. Assigning to *ptr writes back to the original variable.
  4. Print the original variable to see the change.
before: ptr -> score [7]
write:  *ptr = 10
after:  score [10]

Exercise: dereference.c

Use *ptr to read and update an int, then print the original variable to show it changed