Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why array index starts from zero in C/C++ ?
An array arr[i] is interpreted as *(arr+i). Here, arr denotes the address of the first array element or the 0th index element. So *(arr+i) means the element is at i distance from the first element of the array. Therefore, array index starts from 0 as initially i is 0 which means the first element of the array.
In this article, we will see examples of C code to understand the reason why an array starts from index 0.
Syntax
data_type array_name[array_size]; // Accessing element: array_name[index] where index starts from 0
Why Array Index Starts from Zero?
The array index starts from zero because it provides better efficiency and fewer calculations during memory address computation for storing the array elements. Languages such as C and C++ use contiguous memory allocation with row−major order. When index starts with 0, the first element maps with the base address automatically.
Memory Address Calculation Formula
The formula for calculating the memory address of array elements when the index starts from '0' and '1' is mentioned below −
In the above formula, we can see that we need an extra subtraction operation for address calculation when the index starts with '1', making it less efficient.
Example: Array Indexing Demonstration
Here is an example of C code where we print elements at different positions along with their memory addresses −
#include <stdio.h>
int main() {
int arr[] = {100, 200, 300, 400, 500};
printf("The given array is: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n\n");
printf("For index 0, arr[0]: %d\n", arr[0]);
printf("*(arr + 0) = %d\n", *(arr + 0));
printf("Address of arr[0] = %p\n\n", (void *)&arr[0]);
printf("For index 1, arr[1]: %d\n", arr[1]);
printf("*(arr + 1) = %d\n", *(arr + 1));
printf("Address of arr[1] = %p\n\n", (void *)&arr[1]);
printf("Address difference: %ld bytes\n",
(char *)&arr[1] - (char *)&arr[0]);
return 0;
}
The given array is: 100 200 300 400 500 For index 0, arr[0]: 100 *(arr + 0) = 100 Address of arr[0] = 0x7ffc24dbfdf0 For index 1, arr[1]: 200 *(arr + 1) = 200 Address of arr[1] = 0x7ffc24dbfdf4 Address difference: 4 bytes
Key Points
- Array indexing from 0 eliminates unnecessary arithmetic operations during address calculation.
- The pointer arithmetic
arr[i]is equivalent to*(arr + i). - Zero−based indexing makes the relationship between array name and first element direct.
- Each array element occupies consecutive memory locations based on the data type size.
Conclusion
Array indexing starts from zero in C because it provides computational efficiency by eliminating extra arithmetic operations during memory address calculations. This design choice makes pointer arithmetic simpler and more intuitive.
