capypad
0 day streak
go / beginner
Snippet

Pointers: Understanding Memory Addresses

Pointers hold the memory address of a value rather than the value itself. The asterisk (*) declares a pointer type, and the ampersand (&) gets the address of a variable. To access the value at the address, you dereference the pointer with *. Pointers enable pass-by-reference semantics, allowing functions to modify the original variable. This is crucial for working with large data structures efficiently.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main
 
import "fmt"
 
func main() {
x := 42
var p *int = &x
 
fmt.Println("Value of x:", x)
fmt.Println("Address of x:", p)
fmt.Println("Value at address:", *p)
 
*p = 100
fmt.Println("New value of x:", x)
 
y := 50
modifyValue(y)
fmt.Println("y after pass by value:", y)
 
modifyPointer(&y)
fmt.Println("y after pass by pointer:", y)
}
 
func modifyValue(val int) {
val = 999
}
 
func modifyPointer(val *int) {
*val = 999
}
Breakdown
1
var p *int = &x
p holds the address of x (type: pointer to int)
2
*p
Dereferences p to get the value at that address (42)
3
*p = 100
Changes the value at the address p points to, x becomes 100
4
modifyValue(y)
Passes copy of y, original unchanged
5
modifyPointer(&y)
Passes address of y, function can modify original