I’m studying pointers in risc v assembly, but seeing a code from my professor made me wonder if he made an error, or if I’m missing something. The exercise was about converting from C to Assembly Risc V, and I thought that, because in C, given a variable array[N]
, array
is a pointer to array[0]
, in assembly it would be similar and by defining ARRAY: .dword 1,2,3,4
, ARRAY
would be the address of the pointer to array[0]
, not the address of array[0]
directly.
The given C code is (only a snippet, the rest is useless)
typedef long long int LONG
LONG vet[10] = {1,9,3,4,3,15,7,8,2,3}
LONG *p
void main (){
p = vet
…
and the associated assembly code is
VET: .dword 1,9,3,4,3,15,7,8,2,3
P: .dword
.text
.globl MAIN
MAIN: la t0, P
la t1, VET
sd t1, (t0)
…
MY DOUBTS
Now: it’s clear to me that the code in C, with p=vet
is assigning the value inside the vet pointer (so the address of vet[0]) to p, so p now points to the memory cell of vet[0]. But, instead, in assembly, it seems to me that with la t0, P
we’re assigning the address of P to t0, with la t1, VET
we’re assigning the address of the vet pointer of t1, and with sd t1, (t0)
we’re putting the value of the address of vet inside p, so p now points to vet, not to vet[0]
MY ATTEMPTS AS ANSWER
So either the code is wrong and should be
VET: .dword 1,9,3,4,3,15,7,8,2,3
P: .dword
.text
.globl MAIN
MAIN: la t0, P
la t1, VET
ld t2, (t1)
sd t2, (t0)
or “VET” in C us actually a symbol for the address of the first element of the array vet[0] and not a the symbol for the address of a pointer, named vet, with inside the address of vet[0]
>Solution :
… assigning the address of the vet pointer…
VET
is not a pointer. VET: .dword 1,9,3,4,3,15,7,8,2,3
makes VET
a label for the data specified by .dword 1,9,3,4,3,15,7,8,2,3
. The value of the label is the address of that data. In assembly, VET
is the address, not a pointer whose value is the address.
(Also, in C, vet
, when defined with LONG vet[10] = {1,9,3,4,3,15,7,8,2,3};
is an array, not a pointer. When that array is used in an expression other than as the operand of sizeof
or the operand of unary &
, it will be automatically converted to the address of its first element.)