Home > Article > Backend Development > Where does the subscript of an array in C language start?
The subscripts of arrays in C language start from 0. Because if the array element index starts from 1, one more subtraction operation needs to be done each time the address is calculated. Therefore, in order to improve efficiency, the subscripts of C language array elements start from 0.
#The subscripts of arrays in the C language start from 0.
The elements in the array are stored in order, and they are stored continuously in the memory in this order. An array element is represented by its name as a whole and its sequential position in the array.
For example: a[0] represents the first element in the array named a.
So, why do the element subscripts of arrays in C language start from 0 instead of 1?
When the array element subscripts start from 0 , the address of each element is calculated as follows:
0th element address: first address (first address 0*4)
1st element address: first address 1*4
The address of the second element: first address 2*4
The address of the i-th element: the first address i*4
When the array element subscript starts from 1, each element The address is calculated as follows:
1st element address: first address
2nd element address: first address (2-1)*4
3rd element Address: First address (3-1)*4
…
Address of the i-th element: First address (i-1)*4
Obviously , if the array element subscript starts from 1, one more subtraction operation needs to be done each time the address is calculated. Therefore, in order to improve efficiency, C language array element indexes start from 0. The high efficiency of C language is reflected in these bits and pieces, and it needs to be slowly realized during learning!
Related recommendations: "c Language Tutorial"
The above is the detailed content of Where does the subscript of an array in C language start?. For more information, please follow other related articles on the PHP Chinese website!