0

I have problems understanding how to compute the memory address of a 2-dimensional array. (For MIPS assembly code)

This is what I found online to calculate the memory address for 2d array: int base[x][y] address = base[index1][index2] Memory Address = (base address) + (index1 * x * sizeOf(int)) +(index2 * sizeOf(int))

Let's say I have a int array [5][5], base address 0x100. I want to find what is the memory address for [4][3] and [2][5].

Anyone can show me an example of how is it like? or are there any alternatives to calculate the memory address? but please do show me an example of how is it being computed.

Thanks.

2
  • I suppose it depends on the programming language. Commented Nov 5, 2013 at 12:41
  • For MIPS assembly code? does that help? Commented Nov 5, 2013 at 12:46

1 Answer 1

1

Let's say I have a int array [5][5], base address 0x100. I want to find what is the memory address for [4][3] and [2][5].

Let's make some assumptions regarding value placement first. Since your language is assembly, there's no limitations on how you would store your arrays. You can store them by rows or by columns, they can be 0-based or 1-based or 17-based. They can even be potentially jagged (arrays of pointers internally). But we'll assume the most natural case - 2D arrays are stored by row, 0-based. That's the C convention, and the easiest to implement in assembly.

That said, the size of your row is 5*sizeof(int) = 20 bytes. So the offset for element [4][3] would be base + sizeof(row)*4 + sizeof(int)*3 = 0x100 + 20*4 + 4*3 = 256 + 80 + 12 = 348.

Similarly, the offset for [2][5] would be 0x100 + 20*2 + 4*5 = 316, except [2][5] is a misnomer - in a zero-based array of size 5 the topmost legal index is 4. [2][5] is the same as [3][0].

EDIT: sizeof(int) is 4 bytes on most modern systems. MIPS has a 64-bit mode, but it's rather exotic; you would've mentioned if you would've targeted that.

sizeof(row): the array has rows of 5 elements, each element is an int. The wording of the question strongly suggests that the array is that of int's.

Sign up to request clarification or add additional context in comments.

4 Comments

if it's like that, will it mean that [3][0] will be 320, [3][1] will be 324, [3][2] - 328, [3][3] 332, [3][4] 336, [3][5] 340, [4][0] 344 [4][1] 348? but that [4][3] is already 348?? I'm confused. and how do you determine sizeOf(row) or sizeof(int)? I don't understand how do you actually derive the answer.
There's no [3][5] (not legally). The indices run from 0 to 4, so that there's 5 elements per row/column. [3][5] is the same element as [4][0].
Even so, [4][2] will be 348?
[4][2] would be 344. 256 + 20*4 + 4*2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.