pointer basics
package main
import "fmt"
func main() {
var p *int
p = new(int)
*p = 1
fmt.Println(p, &p, *p)
}
Output
0xc04204a080 0xc042068018 1
Go
*
represents the value stored in the pointer address, &
is the address to take a value. For the pointer, it’s important to understand that the pointer stores the address of a value, but the pointer itself also needs the address to store
As above p
is a pointer whose value is memory address 0xc04204a080</code b> and
p
memory address 0xc042068018
memory address 0xc04204a080
memory address 0 1
1
The
error instance
In golang if we define a pointer and assign it to it like a normal variable, such as the code below
package main
import "fmt"
func main() {
var i *int
*i = 1
fmt.Println(i, &i, *i)
}
Would have reported such an error
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x1 addr=0x0 pc=0x498025]
The reason for this error is that go
when you initialize the pointer it gives the pointer I
and it gives the pointer nil
, but I
is the address of * I
, 0 nil
1 the system doesn’t give the address of 2 * I
3, So there’s definitely an error in assigning * I
and it’s very easy to solve this problem, you can just create a block of memory to allocate to an assignment object before you assign to a pointer
package main
import "fmt"
func main() {
var i *int
i = new(int)
*i = 1
fmt.Println(i, &i, *i)
}
Read More:
- Go start error: Panic: runtime error: invalid memory address or nil pointer reference
- panic: runtime error: index out of range
- Free(): invalid pointer error when libtorch runs under Linux
- The @ Autowired annotation in springboot is invalid in ordinary classes. How to solve and use the null pointer exception java.lang.nullpointerexception
- When the spring MVC project is running on idea, an error is reported when the controller is a null pointer
- [debug notes] pointer error when STD:: vector is used in VTK “access conflict when reading location XXX”
- How to use C + + function pointer array
- Python call DLL pointer parameter
- Use of HQL query.list () is a null pointer exception, but the database can find out the result
- Error in dev C + + running pointer
- Failed to get the resources path in the jar package, reporting an error null pointer
- Runtime error 5 Invalid procedure call or argument
- ISO C++ forbids comparison between pointer and integer [-fpermissive]
- Solution to null pointer error in array
- Solve the interceptor calling service layer to display null pointer.
- Two dimensional array and pointer to one dimensional array
- Abnormal crash of APP startup — pointer being free was not allocated * * set a breakpoint in malloc_ error_ break to debug
- ValueError: The field admin.LogEntry.user was declared with a lazy reference to ‘MyApp.sysusers‘
- Error response from daemon: OCI runtime create failed: container_linux.go:380
- Solution: when cmake is compiled, “error in configuration process project files may be invalid” appears