edit: this is using AT&T syntax
I am learning assembly using the GAS assembler and have to write a program where i compare the int value in an array and change the value based on the comparison. I am writing it using inline assembly in C. I know that for a basic variable, say int i, i store the value in register eax with the following line:
movl i, %eax
but now say i have a variable a[2][2] and i want to move a[1][1] into %eax. the obvious wrong answer is:
movl a[1][1], %eax
and i get the error junk ‘[1][1]’ after the expression. How do i go about moving the value of a 2d array into a register? thanks!
It’s up to you to turn the a[1][1] into a linear address. In other words, we have to take
a[1][1]and figure out how far that is from the beginning ofa. We start by figuring the size of a row — in this case, 2 ints. So, (working in ints, for the moment) the beginning of row 0 is at offset 0 from a, row 1 at offset 2, and (if there were more rows) so on. We then add on the offset within that row. Finally, we scale that by the size of a single item.From there, we have a couple of possibilities. One is that we just need a fixed position — we’re going to get
a[1][1], no matter what. The other is that we’re really looking ata[i][j], whereiandjhappen to be 1 at the moment, but could be other sizes.For the first, we can use the fact that the assembler can do some math to compute the address for us.
In the second case, let’s assume we have
iinesiandjinebx. In this case, we have to do the math ourselves (sorry, for the moment I’m going to use Intel syntax — I’m just a lot more accustomed to it):The x86 can actually combine some operations like this that are common for addressing, so you don’t have to execute them as separate instructions as I have above, so we could pretty easily reduce that to:
That last may require a bit of explanation — at least with MASM (and probably with gas, I’d guess) the assembler knows that since you’re loading a value into
eaxthat you’re working in 4-byte quantities, so it automatically scales the offset by 4.