In C, when I define an array like int someArray[10], does that mean that the accessible range of that array is someArray[0] to someArray[9]?
            Asked
            
        
        
            Active
            
        
            Viewed 62 times
        
    0
            
            
         
    
    
        Liam Marshall
        
- 1,353
- 1
- 12
- 21
- 
                    that is true my friend – Ryan Mar 24 '15 at 03:08
- 
                    See also [Why does indexing start with zero in C?](http://stackoverflow.com/questions/7320686/why-does-the-indexing-start-with-zero-in-c) — and there are numerous other related questions too. – Jonathan Leffler Mar 24 '15 at 03:20
- 
                    I understood that indexing is 0-based in c, I just didn't understand that an defining an array `...[10]` meant 0...9 and not 0...10 :D – Liam Marshall Mar 24 '15 at 14:10
3 Answers
4
            
            
        Yes, indexing in c is zero-based, so for an array of n elements, valid indices are 0 through n-1.
 
    
    
        MooseBoys
        
- 6,641
- 1
- 19
- 43
2
            
            
        Yes, because C's memory addressing is easily computed by an offset
myArray[5] = 3
roughly translates to
store in the address myArray + 5 * sizeof(myArray's base type)
the number 3.
Which means that if we permitted
myArray[1]
to be the first element, we would have to compute
store in the address myArray + (5 - 1) * sizeof(myArray's base type)
the number 3
which would require an extra computation to subtract the 1 from the 5 and would slow the program down a little bit (as this would require an extra trip through the ALU.
Modern CPUs could be architected around such issues, and modern compilers could compile these differences out; however, when C was crafted they didn't consider it a must-have nicety.
 
    
    
        Edwin Buck
        
- 69,361
- 7
- 100
- 138
- 
                    For one-based indices, there is no extra trip through the MMU. An additional arithmetic operation is required, but no access to memory happens, until the final address has been calculated. – IInspectable Apr 02 '15 at 11:55
- 
                    Sorry, I meant ALU, but I guess my typing "muscle memory" worked against me this time. – Edwin Buck Apr 02 '15 at 12:55
1
            
            
        Think of an array like this:
* 0   1   2   3   4   5   6   7   8   9
+---+---+---+---+---+---+---+---+---+----+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
+---+---+---+---+---+---+---+---+---+----+
                DATA
* = array indices
So the the range of access would be [0,9] (inclusive)
 
    
    
        Ryan
        
- 14,392
- 8
- 62
- 102