Using Pointers in a for loop

后端 未结 2 442
说谎
说谎 2020-12-03 14:01

I\'m struggling to understand why I have a bug in my code in one state but not the other. It\'s been a while since I\'ve covered pointers, so I\'m probably rusty!

Ba

2条回答
  •  忘掉有多难
    2020-12-03 14:25

    I faced a similar issue today and creating this simple example helped me understand the problem.

    // Input array of string values
    inputList := []string {"1", "2", "3"}
    // instantiate empty list
    outputList := make([]*string, 0)
    
    for _, value := range inputList {
        // print memory address on each iteration
        fmt.Printf("address of %v: %v\n", value, &value)
        outputList = append(outputList, &value)
    }
    
    // show memory address of all variables
    fmt.Printf("%v", outputList)
    

    This printed out:

    address of 1: 0xc00008e1e0
    address of 2: 0xc00008e1e0
    address of 3: 0xc00008e1e0
    [0xc00008e1e0 0xc00008e1e0 0xc00008e1e0]
    

    As you can see, the address of value in each iteration was always the same even though the actual value was different ("1", "2", and "3"). This is because value was getting reassigned.

    In the end, every value in the outputList was pointing to the same address which is now storing the value "3".

提交回复
热议问题