0

if im writing a function that takes a string as an argument how would I traverse the string?

I thought we have to multiply the index by 8 since RISC-V is byte addressible. ex

slli x5, x5, 3 ;; x6 contains index i

add a0, a0, x6 ;; a0 contains address of arg string at index i

lb x6, 0(a0)

This is how I thought I would get char I in the string, but apparently I'm wrong. Do we only multiply but 8 for doublewords? if so, do we multiply by 4 for words, 2 for halfwords, and nothing for chars?

If a0 was an array of long long ints, then I know for sure we slli by 3 (multiply by 8), so I'm guessing we multiply based on the amount of bytes a given data type naturally takes.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Rappterr
  • 1
  • 1
  • 2
    Your guess at the end is correct. Characters (ascii) are 1 byte each and addressing uses bytes. So no multiplication needed. – Jester Oct 26 '22 at 22:14
  • Right, an offset of `n` chars relative to the start of the array is `n * sizeof(char)` bytes, `n*1`. IDK why you initially thought you'd multiply by 8 for characters; RISC-V is byte-addressable not bit-addressable. Anyway, you can always compile a C function like `int foo(char *p, long idx){ return p[idx]; }` on https://godbolt.org/ – Peter Cordes Oct 26 '22 at 22:14
  • Related: [RISC-V how to use each lb, sa, li and how to properly use its syntax](https://stackoverflow.com/q/70913658) - byte vs. `sizeof(T)` scaling is buried in there somewhere. – Peter Cordes Oct 26 '22 at 23:15

0 Answers0