简体   繁体   中英

Different ways to traverse arrays in RISC-V

I'm currently learning about basic assembly language via RISC-V, and I'm slightly confused on valid ways to loop through an array.

If we're given a0 as a pointer to an integer array, would this suffice to move to the next element?

  • lw s0, 0(a0) #pointer to array is stored in s0
  • lw s0 4(s0) #call this each time you want to move to the next element?

If I would want to modify the actual value of the element at the location as well, can I simply use sw?

I also know using slli/srli also allows you to shift, can anyone explain that concept?

Thank you!

The basic pattern for traversing an array (with n elements) is this:

  1. store the array start address in register X
  2. store the address after the last element in register Y (eg Y = X + n * 4 ) with shift and add instructions
  3. dereference X (ie lw to load the word from the address that is present in X) and do something with that array element
  4. increment X by word size (eg 4 bytes) with an add instruction
  5. branch to step 3. if X is still less than Y
  6. traversal is done

Regarding modification: You modify the loaded array element in a register and then you can store the new register value back into your array with sw .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM