CodeBlanks Logo Icon CodeBlanks

What is a pointer?

Learn that a pointer is a memory address.

What is a pointer?

A pointer is a variable that holds the memory address of another variable. The type *int means "the address of an int". With a pointer you can reach and change the same value from several places.

x := 10
p := &x          // p holds x's address
fmt.Println(*p)   // 10: the value at the address
*p = 20
fmt.Println(x)    // 20: x changed

Go has no pointer arithmetic (you can't do p++ as in C); this prevents most memory bugs.

When to use pointers

Pointers are used in two cases: when a function must change the caller's variable, and when you want to share a large value without copying it. For small values (numbers, small structs) a copy is usually simpler and faster. Slices, maps and channels already carry a reference inside; they rarely need pointers.

Practice Change through a pointer

Declare x := 10 and take p := &x. Triple x with *p = *p * 3 and print x and *p on one line.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    x := 10
    p := &x
    *p = *p * 3
    fmt.Println(x, *p)
}

Expected output

30 30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Right after <code>var p *int</code> is declared, what is <code>p</code>'s value?

  • A compile error
  • nil Correct answer
  • 0
  • A random address

Explanation: The zero value of a pointer is nil; it doesn't point at anything yet.

2 Value at the address

Question
x := 5
p := &x
fmt.Println(____p)  // 5
Answer
x := 5
p := &x
fmt.Println(*p)  // 5

Explanation: *p reads the value the pointer points to.

3 Expression and meaning

Term Meaning
*int Pointer-to-int type
&x Address of x
*p Value at the address
nil Empty pointer

All lessons in Beginner