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

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

    first of all you need to know that arrays are internally considered as pointers because the "name of array itself contains the address of the first element of array "

    ex. int arr[2] = {5,4};
    

    consider that array starts at address 100 so element first element will be at address 100 and second will be at 104 now, consider that if array index starts from 1, so

    arr[1]:-
    

    this can be written in the pointers expression like this-

     arr[1] = *(arr + 1 * (size of single element of array));
    

    consider size of int is 4bytes, now,

    arr[1] = *(arr + 1 * (4) );
    arr[1] = *(arr + 4);
    

    as we know array name contains the address of its first element so arr = 100 now,

    arr[1] = *(100 + 4);
    arr[1] = *(104);
    

    which gives,

    arr[1] = 4;
    

    because of this expression we are unable to access the element at address 100 which is official first element,

    now consider array index starts from 0, so

    arr[0]:-
    

    this will be resolved as

    arr[0] = *(arr + 0 + (size of type of array));
    arr[0] = *(arr + 0 * 4);
    arr[0] = *(arr + 0);
    arr[0] = *(arr);
    

    now, we know that array name contains the address of its first element so,

    arr[0] = *(100);
    

    which gives correct result

    arr[0] = 5;
    

    therefore array index always starts from 0 in c.

    reference: all details are written in book "The C programming language by brian kerninghan and dennis ritchie"

提交回复
热议问题