KER
KER

Reputation: 71

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?

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!

Upvotes: 3

Views: 12789

Answers (1)

maxschlepzig
maxschlepzig

Reputation: 39047

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 (e.g. Y = X + n * 4) with shift and add instructions
  3. dereference X (i.e. 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 (e.g. 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.

Upvotes: 7

Related Questions