How exactly pointer subtraction works in case of integer array?

前端 未结 4 548
自闭症患者
自闭症患者 2020-12-17 05:51
#include
int main()
{
    int arr[] = {10, 20, 30, 40, 50, 60};
    int *ptr1 = arr;
    int *ptr2 = arr + 5;
    printf(\"Number of elements between          


        
4条回答
  •  北海茫月
    2020-12-17 06:18

    If you have two pointers of type T that point to elements of the same array then the difference of the pointers yields the number of elements of type T between these pointers

    So the first output statement

    printf("Number of elements between two pointer are: %d.", 
                                (ptr2 - ptr1));
    

    outputs 5 - the number of elements of type int between pointers ptr1 and ptr2.

    It is the so-called pointer arithmetic.

    Pointers (char*)ptr1 and (char*)ptr2 have the same values as the original pointers ptr1 and ptr2 but they consider (reinterpret) the memory extent as an array of type char each element of which has size equal to sizeof( char ). In C sizeof( char ) is always equal to 1. Thus the difference ( char * )ptr2 - ( char * ) ptr1 gives the number of elements of type char that can fit the memory extent. It is evident that sizeof( char ) is not greater than sizeof( int ). So the same memory extent can accomodate more elements of type char than of type int. If for example sizeof( int ) is equal to 4 then the memory extent can accomodate 5 * sizeof( int ) elements of type char that is 20.

提交回复
热议问题