I am from a C background and passing an array in C style causes an error.
package main
import "fmt"
func f(a *int){
fmt.Println(a[1])
}
func main(){
var a [100]int
a[1]=100
f(a)
}
Error:: cannot use a (type [100]int) as type *int in argument to f
As others have mentioned in comments, you probably want to use a slice rather than an array. Slices are passed by reference already, so no need to specify pointers. The make
statement below creates a slice of ints (backed by an array). In the code below, I gave it a length of 2 and a capacity of 100 in order to satisfy your goal of assigning to index 1.
import (
"fmt"
)
func f(a []int) {
fmt.Println(a[1])
}
func main() {
a := make([]int, 2, 100)
a[1] = 100
f(a)
}
To answer the original question, you can pass a pointer to the array, to pass the array by reference.
For example, the following function changes the contents of an array of 3 integers.
func change(ptr *[3]int) {
ptr[2] = 20
}
You can call this by passing a pointer to the original array:
change(&arr)
Complete Example:
package main
import (
"fmt"
)
func main() {
grades := [3]int {1, 2, 3}
fmt.Printf("\nOriginal array:\n")
for i, v := range grades {
fmt.Printf("arr[%d] = %d\n", i, v) // prints 1 2 3
}
change(&grades)
fmt.Printf("\nModified grades:\n")
for i, v := range grades {
fmt.Printf("arr[%d] = %d\n", i, v) // prints 1 2 20
}
}
func change(ptr*[3]int) {
ptr[2] = 20
}
In your example, f
is expecting a pointer to an integer,
func f(a *int) // a points to an integer
and you are passing it an array,
var a [100]int
f(a)
hence it gives you the error cannot use a (type [100]int) as type *int in argument to f
.
Although passing a pointer to an array is efficient and allows the called function to change the caller’s variable, arrays are still fixed in size. Hence, slices are recommended, which are passed by reference and are dynamic in size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With