Home »
Golang
Go Pointer to Pointer (Double Pointer)
Last Updated : July 17, 2025
In Go, a pointer to a pointer (also called a double pointer) is a pointer that stores the address of another pointer. Although not commonly used in Go compared to C/C++, they can be helpful in scenarios where you need to modify a pointer from within a function.
Understanding Pointer to Pointer
A double pointer allows indirect manipulation of a pointer variable. It has the type **T
, where T
is the underlying type.
Example
The following example demonstrates the concept of single and double pointers in Go, showing how to access a value through multiple levels of indirection:
package main
import "fmt"
func main() {
var x int = 10
var p *int = &x
var pp **int = &p
fmt.Println("Value of x:", x)
fmt.Println("Value via single pointer:", *p)
fmt.Println("Value via double pointer:", **pp)
}
When executed, this program outputs:
Value of x: 10
Value via single pointer: 10
Value via double pointer: 10
Here, p
points to x
, and pp
points to p
. So **pp
gives the original value.
Modifying Pointer Using Double Pointer
You can use a double pointer to change where a pointer points inside a function.
Example
The following example demonstrates how to change the address a pointer points to by using a pointer to a pointer:
package main
import "fmt"
func changePointer(pp **int, newVal *int) {
*pp = newVal
}
func main() {
a := 100
b := 200
ptr := &a
fmt.Println("Before change:", *ptr)
changePointer(&ptr, &b)
fmt.Println("After change:", *ptr)
}
Output:
Before change: 100
After change: 200
Here, the function changes the original pointer ptr
to point to a new variable.
Use Cases of Double Pointers
- Useful when you want a function to modify the actual pointer, not just the value it points to.
- Rare in Go, but can be helpful in custom memory structures, tree manipulation, or simulation of C-style pointer behavior.
Example: Function Setting Pointer
The following example demonstrates how a function can assign a new address to a pointer using a pointer to a pointer:
package main
import "fmt"
func setPointer(pp **int) {
val := 999
*pp = &val
fmt.Println("Inside function:", **pp)
}
func main() {
var p *int
setPointer(&p)
fmt.Println("Outside function:", *p)
}
Output may vary because val
inside the function will go out of scope, leading to a potential undefined behavior. So be cautious when returning pointers to local variables.
Exercise
Choose the correct answers based on double pointers in Go.
- What is the type of a pointer to a pointer to an int?
- What does
**pp
give when pp
is a double pointer?
- Is it safe to return the address of a local variable as a pointer?
Advertisement
Advertisement