How exactly pointer subtraction works in case of integer array?

前端 未结 4 554
自闭症患者
自闭症患者 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:24

    To quote C11, chapter §6.5.6, Additive operators

    When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

    So, when you're doing

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

    both ptr1 and ptr2 are pointers to int, hence they are giving the difference in subscript, 5. In other words, the difference of the address is counted in reference to the sizeof().

    OTOH,

     printf("Number of bytes between two pointers are: %d",  
                              (char*)ptr2 - (char*) ptr1);
    

    both ptr1 and ptr2 are casted to a pointer to char, which has a size of 1 byte. The calculation takes place accordingly. Result: 20.

    FWIW, please note, the subtraction of two pointers produces the result as type of ptrdiff_t and you should be using %td format specifier to print the result.

提交回复
热议问题