How does a program find an array index?

I know that searching in an array has O (1) time, so it cannot go through a circular transition. Does the memory store the index space of the array or what does it look like instantly?

+6
source share
4 answers

Array elements are always located at equal distances in memory, therefore, to find an element with a given index, multiplication by the element size and adding the array base to the memory are required. Both operations are often performed in the space of a single command on the hardware using the appropriate addressing mode.

+9
source

under ... its memory address + (postion pointer * the size of things in the array)

+3
source

Try it,

1. Arrays are consecutive memory locations which are stored in Heap, as Arrays are objects in java.

2. Assume i have an Array of String as an instance variable

String [] arr = {1,2,3,4,5};

Now it looks like

arr [0] = 1

arr [1] = 2

arr [2] = 3

arr [3] = 4

arr [4] = 5

{1,2,3,4,5} are stored over the heap, and Considering array "arr" as instance variable, will lives within the object on the heap.

Now arr will contain the address of the very first element of the array, which is 1 . "arr", which is a variable of an array of objects, will be inside the object and {1,2,3,4,5} out of the heap.

0
source

The elements of the array are stored in a sequential block, if they grow, they need to be moved to a new location. Elements are then accessed using an offset from the beginning of the array.

In C, you can access the index element i in an array named a using two different methods:

  • int arrayElement = a[i];
  • int arrayElement = (int)(a + i * sizeof(int));

This is more or less how it is done in Java under the hood.

0
source

Source: https://habr.com/ru/post/919083/


All Articles