Why does the indexing start with zero in 'C'?

前端 未结 16 2592
执念已碎
执念已碎 2020-11-22 16:22

Why does the indexing in an array start with zero in C and not with 1?

16条回答
  •  广开言路
    2020-11-22 16:36

    Because 0 is how far from the pointer to the head of the array to the array's first element.

    Consider:

    int foo[5] = {1,2,3,4,5};
    

    To access 0 we do:

    foo[0] 
    

    But foo decomposes to a pointer, and the above access has analogous pointer arithmetic way of accessing it

    *(foo + 0)
    

    These days pointer arithmetic isn't used as frequently. Way back when though, it was a convenient way to take an address and move X "ints" away from that starting point. Of course if you wanted to just stay where you are, you just add 0!

提交回复
热议问题