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

前端 未结 16 2291
执念已碎
执念已碎 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:54

    In array, the index tells the distance from the starting element. So, the first element is at 0 distance from the starting element. So, that's why array start from 0.

    0 讨论(0)
  • 2020-11-22 16:55

    In C, the name of an array is essentially a pointer [but see the comments], a reference to a memory location, and so the expression array[n] refers to a memory location n elements away from the starting element. This means that the index is used as an offset. The first element of the array is exactly contained in the memory location that array refers (0 elements away), so it should be denoted as array[0].

    For more info:

    http://developeronline.blogspot.com/2008/04/why-array-index-should-start-from-0.html

    0 讨论(0)
  • 2020-11-22 16:56

    Try to access a pixel screen using X,Y coordinates on a 1-based matrix. The formula is utterly complex. Why is complex? Because you end up converting the X,Y coords into one number, the offset. Why you need to convert X,Y to an offset? Because that's how memory is organized inside computers, as a continuous stream of memory cells (arrays). How computers deals with array cells? Using offsets (displacements from the first cell, a zero-based indexing model).

    So at some point in the code you need (or the compiler needs) to convert the 1-base formula to a 0-based formula because that's how computers deal with memory.

    0 讨论(0)
  • 2020-11-22 16:59

    I am from a Java background. I Have presented answer to this question in the diagram below which i have written in a piece of paper which is self explanatory

    Main Steps:

    1. Creating Reference
    2. Instantiation of Array
    3. Allocation of Data to array

    • Also note when array is just instantiated .... Zero is allocated to all the blocks by default until we assign value for it
    • Array starts with zero because first address will be pointing to the reference (i:e - X102+0 in image)

    Note: Blocks shown in the image is memory representation

    0 讨论(0)
提交回复
热议问题