stringgopointerscharactermemory-address

How to print a string from address and size


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
    }
}

Solution

  • 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)                                  
        }
    }
    

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