Pointers Made Easy
Understand pointers and how they allow functions to modify values.
Learning objective: Use pointers to pass a variable address into a function.
What Is a Pointer?
A pointer stores the memory address of a value. Pointers are useful when you want a function to modify an existing value.
Using & and *
The & operator gets the address of a variable. The * operator accesses the value stored at that address.
Pointer Parameters
Passing a pointer to a function allows the function to update the original variable.
Example Code
Create or update your Go file, then run the program using go run main.go.
package main
import "fmt"
func increase(score *int) {
*score = *score + 10
}
func main() {
marks := 70
increase(&marks)
fmt.Println("Updated marks:", marks)
}
Key points to remember
- Use & to pass the address of a variable.
- Use * to access or update the value through the pointer.
- Pointers are common in methods that modify struct values.
Practice Exercises
- Print the address of a variable.
- Write a function that changes a value using a pointer.
- Explain the difference between & and * in your own words.
Continue Learning
After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.