Hello, I have strange behavior when using pointer. Can please someone explain how is it working?
package main
import "fmt"
func addAndCheck(candidates []int, candidateIndex int, target int, currentTest []int, l int, finalSolution *[][]int) {
currentTest = append(currentTest, candidates[candidateIndex])
if target == 0 {
fmt.Println("currentTest --> ", currentTest)
*finalSolution = append(*finalSolution, currentTest)
fmt.Println("current finalResult --> ", *finalSolution)
return
}
if target < 0 {
return
}
for i := candidateIndex; i < l; i++ {
//fmt.Println(target, candidates[i], i, target-candidates[i], currentTest )
addAndCheck(candidates, i, target-candidates[i], currentTest, l, finalSolution)
}
}
func combinationSum(candidates []int, target int) [][]int {
solution := make([][]int, 0)
for i, k := range candidates {
currentTest := make([]int, 0)
addAndCheck(candidates, i, target-k, currentTest, len(candidates), &solution)
}
return solution
}
func main() {
a := combinationSum([]int{2, 3, 5}, 8)
fmt.Println("finalResult --> ", a)
}
As you can see in from the code I am appending the result which works for me in the finalResult array. The weird things happens with the first pushed element of the array. Here is the output i receive when printing out the currentTest and finalResult during program execution.
currentTest → [2 2 2 2]
current finalResult → [[2 2 2 2]]
currentTest → [2 3 3]
current finalResult → [[2 2 2 5] [2 3 3]]
currentTest → [3 5]
current finalResult → [[2 2 2 5] [2 3 3] [3 5]]
finalResult → [[2 2 2 5] [2 3 3] [3 5]]
How is it possible that first pushed slice [2 2 2 2] is turning into [2 2 2 5] ?
Thank you for your help in advance.