How exactly indexing works in Arrays?

Technology CommunityCategory: ArraysHow exactly indexing works in Arrays?
VietMX Staff asked 3 years ago

Arrays will always be laid out in memory using consecutive storage locations. Most languages model arrays as contiguous data in memory, of which each element is the same size. Let’s say we had an array of int’s:

[0: 10][32: 20][64: 30][96: 40][128: 50][160: 60]

Each of these elements is a 32-bit integer, so we know how much space it takes up in memory (32 bits). And we know the memory address of the pointer to the first element. It’s trivially easy to get to the value of any other element in that array:

  • Take the address of the first element (the compiler knows the array to start at memory cell x)
  • Take the offset of each element (its size in memory)
  • Multiply the offset by the desired index
  • Add your result to the address of the first element

It always takes one multiplication, one add operation and one fetch of an element from a know location.