Josh Newlin
Josh Newlin

Reputation: 108

How do you point to a value in an array in ARM assembly?

So I need to point to a specific value in the array. I don't know how to get the address though, so for example what I need to do (in C) is this call a function like this,

int p = 5;
cqs(&a[0], p);
cqs(&a[p+1], n-p-1);

How would I point to the specific index in ARM? I've tried

ldr r6, [r0, r3, asl #2]
ldr r0, =r6
bl cqs

but the compiler doesn't like that.

Can someone help?

Upvotes: 0

Views: 1429

Answers (2)

Michael
Michael

Reputation: 58437

Assuming that you have the base address in r0, the (variable) index in r3, and the size of each element is 4 bytes:

add r0, r0, r3, lsl#2    @ r0 += r3 * 4 

Upvotes: 1

Peter Cordes
Peter Cordes

Reputation: 364160

Address math is just integer add/subtract.

Looking at C compiler output is one way to learn asm.

void cqs(int *);

int arrayptr(int *a) {
  int p = 5;
  cqs(&a[p+1]);
  return 0;
}

compile to (godbolt ARM gcc 4.8)

arrayptr(int*):
    push    {r3, lr}    @
    adds    r0, r0, #24 @, a,
    bl  cqs(int*)   @
    movs    r0, #0  @,
    pop {r3, pc}    @

So adds dest, src, imm looks like a good way to offset an array pointer to point farther along in the array.

The return 0; stops gcc from tail-call optimizing the function call into a jump.

Upvotes: 0

Related Questions