doudu8291 2018-01-31 14:12
浏览 6
已采纳

指向结构的指针更改未反映在调用者中

I am passing a pointer to the struct to another function named someFunc() and changing there, but it's not reflecting in caller function in this case main().

type Slot struct {
  f1 int
  f2 string
  f3 []*string
}

func NewSlot(f1, f2){
  return &Slot{f1: f1, f2: f2, f2: make([]*string, 0)}
}

func main() {

  slots := &Slots{}
  scanner := bufio.NewScanner(os.Stdin)
  for scanner.Scan() {
    s := scanner.Text()
    sarr := strings.Split(s, " ")
    fmt.Println("scanner", slots)
    someFunc(slots, sarr[0], sarr[1:]...)
  }
 }
func someFunc(slots *Slots, cmd string, args ...string) {
  slots = NewSlots(5) // return Pointer to slots with 5 and other value initialized

  // But not reflecting to main() func, Why?
}
  • 写回答

1条回答 默认 最新

  • duanlu9816 2018-01-31 14:49
    关注

    I found this working with the help of @adrian. This is how it worked.

    func main() {
    
      slots := &Slots{}
      scanner := bufio.NewScanner(os.Stdin)
      for scanner.Scan() {
        s := scanner.Text()
        sarr := strings.Split(s, " ")
        fmt.Println("scanner", slots)
        someFunc(&slots, sarr[0], sarr[1:]...)
      }
     }
    func someFunc(slotsPtr **Slots, cmd string, args ...string) {
      *slotsPtr = NewSlots(5) // return Pointer to slots with 5 and other value initialized
    
      // and used *slotsPtr in rest of the program
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题