英文:
How to print a string from address and size
问题
我想通过使用for循环从地址打印一个字符串。
以下是我编写的代码,但在正常运行和调试时给出了不同的结果。
如何按顺序通过字符串的地址逐个打印每个字符。
请帮帮我。非常感谢你 <3
这是我的代码!!!
package main
import (
"fmt"
"unsafe"
)
func main() {
str := "Hello, World!"
startAddr := uintptr(unsafe.Pointer(&str)) // 获取字符串变量的地址
for i := 0; i < len(str); i++ {
ptr := (*byte)(unsafe.Pointer(startAddr + uintptr(i))) // 计算指针地址
fmt.Printf("%c", *ptr) // 解引用指针以获取字符
}
}
英文:
I want to print a string from address by for loop.
Below is the code that I wrote, but it gives different results when running normally and when debugging.
How can I print each char of str sequentially by address of str.
Plss help me. Tks you so muchhhh <3
This is my code!!!
package main
import (
"fmt"
"unsafe"
)
func main() {
str := "Hello, World!"
startAddr := uintptr(unsafe.Pointer(&str)) // Get the address of the string variable
for i := 0; i < len(str); i++ {
ptr := (*byte)(unsafe.Pointer(startAddr + uintptr(i))) // Calculate the pointer address
fmt.Printf("%c", *ptr) // Dereference the pointer to get the character
}
}
答案1
得分: 2
你的尝试不起作用的原因是&str
返回的是字符串的头部地址,而不是字符串数据的地址。如果你想要字符串数据的地址,你需要先将&str
转换为字符串头部,然后通过头部访问数据。你可以使用声明的reflect.StringHeader
来实现这一点,确保你阅读了它的文档并理解了其中的内容。
func main() {
str := "Hello, World!"
header := (*reflect.StringHeader)(unsafe.Pointer(&str))
for i := 0; i < len(str); i++ {
ptr := (*byte)(unsafe.Pointer(header.Data + uintptr(i)))
fmt.Printf("%c", *ptr)
}
}
https://go.dev/play/p/kniSJyM7DX5
英文:
The reason your attempt doesn't work is because &str
returns the address of the string header, not of the string's data. If you want the address of the string's data you need to first convert &str
into a string header, and then access the data through the header. You can use the declared reflect.StringHeader
to do this, just make sure you read its documentation and understand what it says.
func main() {
str := "Hello, World!"
header := (*reflect.StringHeader)(unsafe.Pointer(&str))
for i := 0; i < len(str); i++ {
ptr := (*byte)(unsafe.Pointer(header.Data + uintptr(i)))
fmt.Printf("%c", *ptr)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论