Pointers
Dereference
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
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;
}
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
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
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
ptrstores the address of an existing variable.*ptrreads the value at that address.- Assigning to
*ptrwrites back to the original variable. - 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