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

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

    Suppose we want to create an array of size 5
    int array[5] = [2,3,5,9,8]

    let the 1st element of the array is pointed at location 100

    and let we consider the indexing starts from 1 not from 0.

    now we have to find the location of the 1st element with the help of index
    (remember the location of 1st element is 100)

    since the size of an integer is 4-bit
    therefore --> considering index 1 the position would be
    size of index(1) * size of integer(4) = 4
    so the actual position it will show us is

    100 + 4 = 104

    which is not true because the initial location was at 100.
    it should be pointing to 100 not at 104
    this is wrong

    now suppose we have taken the indexing from 0
    then
    position of 1st element should be
    size of index(0) * size of integer(4) = 0

    therefore -->
    location of 1st element is 100 + 0 = 100

    and that was the actual location of the element
    this is why indexing starts at 0;

    I hope it will clear your point.

提交回复
热议问题