Why is the subscript of the first element of the array 0

Based on various information on the Internet, the ideas are sorted out:

From the perspective of the storage data model of the array, the subscript can be understood as an "offset".

Therefore, the offset of the first element a[0] in the array is 0, which is the first address (base_address).

By analogy, the offset of the array element a[i] is i, and the addressing formula is:

a[i] = base_address + i * type_size

That is, the first address + i * the number of bytes of the array type (the memory size of each element)

On the contrary, if the numbering of the first element starts from 1, the addressing formula of the array element a[i] is:

a[i]= base_address + (i - 1) * type_size

That is, the first address + (i - 1) * memory size of each element

In this way, each random access to the array elements will add one more subtraction operation, and starting from 0, one subtraction operation can be reduced, which is more efficient from the perspective of algorithm optimization.

  

Guess you like

Origin blog.csdn.net/Nebula_W/article/details/130097923