Saturday, 28 May 2016

Why array index in C and C++ was starting with zero(0) instead of one(1)?

No comments:
Because arrays are implemented similar to pointers in c and c++.
Array is not completely a pointer, but arrays  behaves like a pointer which will depend upon the situation where you were using in code.
Now consider one int array example:
int a[10];
In the above int array example, I have declared int array a with size as 10.
Here compiler will allocate memory continuously with first element of the array pointing to the first element.
Consider element of the first address as 1000.
Just hold on up to here, let me teach you about subscript operator.

What is array subscript operator in C or C++?

            Operator which is used to access the array element is called array subscript operator or index operator.
Array index operator [] example:
            int a[10];
How this index operator works in c or c to access array element?
Consider you were accessing third element in array like a[2]
Here how compiler will access the third element is like following
Compiler will change the a[2] in to  (base address of a + 2).
Hope you noticed. So, whatever number you were giving accessing array element, compiler will add it to array base address and it will access the element.
So how to access the 1st element in the array.
You have to add 0 to the base address. The base address of the array contains the 1st value of the array .i.e., arr[0]. Compiler uses the a+0.  To This is the reason array index is starting with zero instead of one.

Another technical reason for array index starting with zero:

Not only for offset purpose the array index was starting with zero.
There is also another reason which is considered by the compiler designers and computer scientists to start the index with 0.
We need to consider how much memory array index value takes to store in memory.
To represent the b power n values we require an n bits to store array index  in memory if index started with 1.
Seems to be confusing, Look at the example below
For Eg, Consider you want to represent the 8 array elements in memory.
If you start with 0 (0-7) we will required for 3 bits to represent in terms of binary.
If you start with 1(1-8) we will be required 4 bits. Because 8 cannot be represented using the 3 bits it requires an additional 4th  bit.
This is the reason why addressing the memory in computer system also starts with zero instead of 1.

No comments:

Post a Comment