Junior — Middle
Explain the principle of a pointer in programming and how it is used to access data.
sobes.tech AI
Answer from AI
A pointer in programming is a variable that stores the address of another variable in memory. In Go, pointers allow working with variable addresses, enabling direct data modification and efficient passing of large structures.
Working principle:
- A pointer contains the memory address where the variable is located.
- You can access the value at this address (dereferencing).
- Used for passing by reference to avoid copying data.
Example in Go:
package main
import "fmt"
func main() {
var a int = 42
var p *int = &a // p is a pointer to a
fmt.Println("Value of a:", a) // 42
fmt.Println("Address of a:", p) // memory address
fmt.Println("Value through pointer:", *p) // 42
*p = 100 // change the value of a through the pointer
fmt.Println("New value of a:", a) // 100
}
Thus, pointers allow efficient memory management and data modification by reference.