DEV Community

Discussion on: Why array indexing in C++ starts from 0, not 1

Collapse
 
patriscus profile image
Patrick Ahmetovic

I will try to explain how I have understood it - please correct me if I'm wrong.

The way I picture arrays in general is as follows:
An array is a certain block in memory. You can think of it as a drawer unit. Each drawer (element in your array) in that unit has a certain height (your data size W).

Now the Base Address(L0) refers to the handle of your first drawer.

If you use the first formula (Logical Address(A[i]) = Base Address(L0) + ( i - 1 ) * W)
You would essentially say the following as an example: I want the 3rd drawer handle, so I look at my first handle (L0) and add the height (W) of 2 (i - 1) drawers to it => then I reach the third handle.

Now instead of refering to the 3rd drawer as A[3], we can use zero-based numbering and refer to it as A[2]. By doing so, we have eliminated the need for the substraction in (i - 1), thus saving us calculations.

I hope that explanation makes sense.

Collapse
 
jouo profile image
Jashua

Thank you very much :D