0
0
Goprogramming~10 mins

Address and dereference operators in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Address and dereference operators
Declare variable x
Use & operator to get address of x
Store address in pointer p
Use * operator to dereference p
Access or modify value at address
End
This flow shows how a variable's address is taken with & and accessed or changed using * to dereference the pointer.
Execution Sample
Go
package main
import "fmt"
func main() {
  x := 10
  p := &x
  fmt.Println(*p)
  *p = 20
  fmt.Println(x)
}
This code shows how to get the address of x, print its value via pointer p, change it through p, and print x again.
Execution Table
StepActionVariableValuePointer ValueOutput
1Declare xx10nil
2Get address of x with &x10address_of_x
3Assign address to ppniladdress_of_x
4Print *p (dereference p)x10address_of_x10
5Set *p = 20 (change value at address)x20address_of_x
6Print x after changex20address_of_x20
💡 Program ends after printing updated value of x
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5Final
xundefined10102020
pnilniladdress_of_xaddress_of_xaddress_of_x
Key Moments - 3 Insights
Why does changing *p also change x?
Because p holds the address of x, dereferencing *p accesses the same memory as x, so changing *p changes x (see steps 5 and 6).
What does the & operator do exactly?
The & operator gets the memory address of a variable, shown in step 2 where p gets the address of x.
Why do we use *p to print the value instead of just p?
p is a pointer holding an address; *p accesses the value at that address, so printing *p shows x's value (step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x after step 5?
A20
B10
Caddress_of_x
Dnil
💡 Hint
Check the 'Value' column for x at step 5 in the execution_table.
At which step is the pointer p assigned the address of x?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column describing pointer assignment in the execution_table.
If we print p instead of *p at step 4, what would be the output?
A10
B20
Caddress_of_x
Dnil
💡 Hint
p holds the address; see the 'Pointer Value' column in the execution_table.
Concept Snapshot
Address and dereference operators in Go:
- & gets the address of a variable
- * dereferences a pointer to access or change the value
- Changing *p changes the original variable
- Use pointers to work with memory addresses directly
Full Transcript
This example shows how to use the address operator & to get a variable's memory address and store it in a pointer variable p. Then, using the dereference operator *, we access or modify the value at that address. Initially, x is 10. We assign p = &x, so p points to x's address. Printing *p shows 10. Changing *p to 20 updates x to 20. Printing x confirms the change. This demonstrates how pointers let us work directly with memory locations in Go.