[Solved] Why does pointer assignment cause variable assignment to not always stick?


The problem is with the pointer assignments as you build the slice you are trying to reference. The addresses keep changing.

func main(){
    var lump []int
    
    // A loop to build a slice of `int`'s from 0 size to 8 size
    // and print each index address
    for i:= 0; i < 8; i++{
        lump = append(lump, int(i))
        fmt.Printf("addr of lump[%v]: %p\n",i, &lump[i])
    }
    
    fmt.Println()
    
    // A loop to look at the addresses of each index
    for i := range lump{
        fmt.Printf("addr of lump[%v]: %p\n",i, &lump[i])
    }
}

Check out the addresses not being created in sequential memory locations.

//while building the slice
// notice the addresses making big jumps
addr of lump[0]: 0xc00000a0c8
addr of lump[1]: 0xc00000a0f8
addr of lump[2]: 0xc00000e3b0
addr of lump[3]: 0xc00000e3b8
addr of lump[4]: 0xc00000c2e0
addr of lump[5]: 0xc00000c2e8
addr of lump[6]: 0xc00000c2f0
addr of lump[7]: 0xc00000c2f8

//after building the slice
// notice all address being sequential
addr of lump[0]: 0xc00000c2c0
addr of lump[1]: 0xc00000c2c8
addr of lump[2]: 0xc00000c2d0
addr of lump[3]: 0xc00000c2d8
addr of lump[4]: 0xc00000c2e0
addr of lump[5]: 0xc00000c2e8
addr of lump[6]: 0xc00000c2f0
addr of lump[7]: 0xc00000c2f8

You could move to C/C++ where you could handle all the memory adjustments as the array increases in size. Or build one slice then the other.

solved Why does pointer assignment cause variable assignment to not always stick?