Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can someone help me figure out why this is not success

package main

import (
    "fmt"
)

func main() {
    arr0 := []int{
        1,2,3,4,5,
    }
    arr1 := []int{}

    fmt.Println(arr0)
    fmt.Println(arr1)
    fmt.Println("transferring...")
    transfer(&arr0, &arr1)
    fmt.Println(arr0)
    fmt.Println(arr1)
}

func transfer(arr0 *[]int, arr1 *[]int) {
    tmp := make([]int, 0)
    for i:=0;i<len(*arr0);i++ {
        tmp = append(tmp, (*arr0)[i])
    }

    arr1 = &tmp
    s := make([]int, 0)
    arr0 = &s
}

For function of transfer, I intented to transfer elements of slice arr0 to slice arr1 and empty slice arr0

But it is not successful

Here is my output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[1 2 3 4 5]
[]
transferring...
[1 2 3 4 5]
[]

After transferring, I need the result below.
[]
[1 2 3 4 5]
But actually, arr0, and arr1 in the main function remain as it was!

can someone tell me why this is not ok?

I thought in the memory, it should be like this

enter image description here

after running transfer function

enter image description here

>Solution :

These two lines:

arr1 = &tmp
arr0 = &s

change the local variables arr1 and arr0 within the function. Those variables happen to be pointers, but they are just copies of the input pointers provided by main—they are not references to the input pointers.

If you changed the things the arr1 and arr0 pointers point to, rather than the pointers themselves, then you would see a change to the values provided by main:

*arr1 = tmp
*arr0 = s
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading