问题
I'm writing an assembly program which I want to be able to do the (basic) following:
x = 100;
y = int[x]
E.g. the size of y depends on the value of x.
NOTE: I am using NASM instruction set on a 64 bit Ubuntu system.
In assembly I know that the size of an array needs to be declared in the data section of the file e.g.
myvariable resq 1000
The problem is I won't know how big to make it till I have done a previous calculation. What I really want is something like:
mov rax, 100
myvariable resq rax
But that's not allowed right? Just having some confusion over array access/declarations in assembly.
Any pointers appreciated!
回答1:
Your C example is only possible if you declare the array on the stack or if you pull the memory from the heap with malloc or similar. For small values its perfectly fine (and faster) to use the stack:
mov rax, 100 # 100 elemtents
shl rax, 3 # muliply with 8, the size of an element
sub rsp, rax # rsp points now to your array
# do something with the array
mov rbx, [rsp] # load array[0] to rbx
mov [rsp+8], rbx # store to array[1]
add rsp, rax # rsp point to the return address again
来源:https://stackoverflow.com/questions/8504097/declaring-variable-sized-arrays-in-assembly