1

I've training / homework to create the following formula applied to C:

How to calculate the address to an element in a matrix of integers, if the starting address of the matrix is known, the size is known and the row and the columns of the element is known.

Say the matrix is a[b][c]. The starting address is then a or equivalently &a[0][0]

Numbers of rows is b.

Number of columns is c.

Every element should have size sizeof(int) so then the address would be a + b*sizeof(int) + a*sizeof(int)

Is this formula correct?

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424

3 Answers3

1

Suppose you have int array[b][c] and you need to find the address of element array[i][j].

a + i * c * sizeof(int) + j * sizeof(int)

where, c * sizeof(int) appears to be a row size, so a general formula for this is

array_start + i * row_size + j * item_size
Maksim Skurydzin
  • 10,301
  • 8
  • 40
  • 53
1

Assuming arrays are stored row-major, that means if you have:

int array[N][M];

Then, first you have M ints corresponding to array[0], then you have M ints corresponding to array[1] and so on.

Therefore:

  • address of array[0][c] is given by: (char *)array + c * sizeof(int)
  • address of array[1][0] is given by: (char *)array + 1 * M * sizeof(int) because there are M int for array[0].
  • address of array[1][c] is given by: (char *)array + 1 * M * sizeof(int) + c * sizeof(int)
  • address of array[2][0] is given by: (char *)array + 2 * M * sizeof(int)
  • You can hopefully see the pattern now. Address of array[r][c] is given by (char *)array + r * M * sizeof(int) + c * sizeof(int) that is, r * M to skipt the first r rows, and then c columns.

You can see this answer for more explanation on 2D memory layout. The same answer also contains memory layout of dynamic arrays.

Community
  • 1
  • 1
Shahbaz
  • 46,337
  • 19
  • 116
  • 182
1

Here's another way to think about it:

First calculate the index of that element, using this equation

i = c + r * w

where c is the column, r is the row and w is the width of the matrix/2D array (the number of columns)

Then multiply that by the size of an integer, that gives you the memory offset of the element from the base address

offset = i * sizeof(int);

Finally, add that to the base address:

addr = base + offset

so the formula is:

addr =  base + (c+r*w) * sizeof(int)
iabdalkader
  • 17,009
  • 4
  • 47
  • 74