Pointers & Memory Addresses

🐹 Go Language Lesson 8 Intermediate

Pointers are variables that store the memory address of other variables. Go supports pointers to improve performance, but prevents dangerous pointer arithmetic.

1 Memory Addresses & Safety (No Pointer Arithmetic)

Go pointers use standard operators: Address-of (`&`) and Dereference (`*`). Unlike C, **Go does not allow pointer arithmetic** (like `ptr + 1`). This prevents variables from pointing to unallocated memory blocks, eliminating common memory corruption and buffer overflow bugs.

2 Pointers Code

Let's run a program declaring pointers, displaying addresses, and modifying values via dereferencing:

Go — Pointer Basics ▶ Run Code
package main

import "fmt"

func main() {
    num := 42
    ptr := &num // ptr stores address of num

    fmt.Printf("Value of num: %d\n", num)
    fmt.Printf("Address of num: %p\n", ptr)
    fmt.Printf("Value via Pointer: %d\n", *ptr)

    // Modify value via pointer dereferencing
    *ptr = 100
    fmt.Printf("Updated value of num: %d\n", num)
}
3 Code Challenge
Challenge: Write a function called `doubleValue` that accepts an integer pointer parameter and doubles the value it points to in memory. Declare an integer in `main()`, call `doubleValue`, and print the result.