Question

I'm building a compiler for a subset of C, and now I'm dealing with arrays. Suppose I have the following:

int main() {
    int x[3];
    x[0] = 1;
    x[1] = 3;
    x[2] = 4;
}

In assembly, the asignments would be like this:

movl    $1, -12(%ebp)
movl    $3, -8(%ebp)
movl    $4, -4(%ebp)

So far, so good. Now if I wanted to access an arbitrary position, stored in %ebx, how should I do it? I've been reading this wikibook but I don't quite get the syntax.

I've tried the following but it does not seem to work:

# Suppose I want to do x[1] = 5
movl $1, %ebx

movl $5, -4(%ebp, %ebx, 4)

What am I missing?

Was it helpful?

Solution

The problem is that the base of the array is not -4(%ebp) but -12(%ebp) (as that's where the first item is placed) so the indexing should be like this:

movl $1, %ebx
movl $5, -12(%ebp, %ebx, 4)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top