CodeBlanks Logo Icon CodeBlanks

& and * operators

Learn the address (&) and dereference (*) operators.

The & and * operators

& takes a variable's address; * is used in two senses: in a type, "pointer" (*int), and in an expression, "the value at the address" (*p, dereference).

ad := "Ada"
p := &ad        // p's type: *string
fmt.Println(*p)  // Ada
*p = "Can"
fmt.Println(ad)  // Can

The address itself can be printed with %p (e.g. 0xc000014070); its value changes on every run.

Comparing pointers

When two pointers are compared with ==, their addresses are compared, not their values. To compare the values, dereference first:

a, b := 5, 5
pa, pb := &a, &b
fmt.Println(pa == pb)    // false: different variables
fmt.Println(*pa == *pb)  // true: same value

Practice Two pointers

Declare a := 1. Take p := &a and q := p, then set *q = 7. Print the value of a and the result of p == q 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() {
    a := 1
    p := &a
    q := p
    *q = 7
    fmt.Println(a, p == q)
}

Expected output

7 true

Questions and answers

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

1 After <code>a := 1; p := &amp;a; q := p; *q = 7</code>, what is <code>a</code>?

  • 7 Correct answer
  • 1
  • 0
  • An error

Explanation: q := p copies the address; p and q point to the same a. *q = 7 changes a.

2 Take the address

Question
sayi := 42
p := ____sayi
Answer
sayi := 42
p := &sayi

Explanation: The & operator gives the variable's address.

3 Code and result (a, b := 5, 5)

Term Meaning
&a == &a true
&a == &b false
*(&a) 5
p := &a; *p = 9 a = 9

All lessons in Beginner