如何根据地址和大小打印字符串

huangapple go评论86阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;unsafe&quot;
)

func main() {
	str := &quot;Hello, World!&quot;
	startAddr := uintptr(unsafe.Pointer(&amp;str)) // Get the address of the string variable

	for i := 0; i &lt; len(str); i++ {
		ptr := (*byte)(unsafe.Pointer(startAddr + uintptr(i))) // Calculate the pointer address
		fmt.Printf(&quot;%c&quot;, *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 &amp;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 &amp;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 := &quot;Hello, World!&quot;
	header := (*reflect.StringHeader)(unsafe.Pointer(&amp;str))

	for i := 0; i &lt; len(str); i++ {
		ptr := (*byte)(unsafe.Pointer(header.Data + uintptr(i)))
		fmt.Printf(&quot;%c&quot;, *ptr)                                  
	}
}

https://go.dev/play/p/kniSJyM7DX5

huangapple
  • 本文由 发表于 2023年7月5日 13:39:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76617386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定