Home > Back-end >  Pointer address of a struct
Pointer address of a struct

Time:10-28

Consider this code :

package main

import "fmt"

type S struct {
    Val  int
}

func main() {
    e1 := S{Val: 1}
    fmt.Printf("%p\n", &e1)
    fmt.Printf("%p\n", &e1.Val)
}

After running it, we'll get something like that:

0xc00001c030
0xc00001c030

What confuses me is why pointer's address of the struct and it's member are the same?

Link to Go Playground: https://go.dev/play/p/Wl4tnD9TFmA

CodePudding user response:

Struct is memory area with all fields put there one by one (if aliment present, then they could be with gaps). Same as array. So first element of struct obviously should have same address as struct itself.

  •  Tags:  
  • go
  • Related