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

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

    It is because the address has to point to the right element in the array. Let us assume the below array:

    let arr = [10, 20, 40, 60]; 
    

    Let us now consider the start of the address being 12 and the size of the element be 4 bytes.

    address of arr[0] = 12 + (0 * 4) => 12
    address of arr[1] = 12 + (1 * 4) => 16
    address of arr[2] = 12 + (2 * 4) => 20
    address of arr[3] = 12 + (3 * 4) => 24
    

    If it was not zero-based, technically our first element address in the array would be 16 which is wrong as it's location is 12.

提交回复
热议问题