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(<type>)
.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…