#include<stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60};
int *ptr1 = arr;
int *ptr2 = arr + 5;
printf("Number of elements between two pointer are: %d.",
(ptr2 - ptr1));
printf("Number of bytes between two pointers are: %d",
(char*)ptr2 - (char*) ptr1);
return 0;
}
For the first printf()
statement the output will be 5
according to Pointer subtraction confusion
What about the second printf()
statement, what will be the output?
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 typeT
between these pointersSo the first output statement
outputs 5 - the number of elements of type
int
between pointersptr1
andptr2
.It is the so-called pointer arithmetic.
Pointers
(char*)ptr1
and(char*)ptr2
have the same values as the original pointersptr1
andptr2
but they consider (reinterpret) the memory extent as an array of typechar
each element of which has size equal tosizeof( char )
. In Csizeof( char )
is always equal to 1. Thus the difference( char * )ptr2 - ( char * ) ptr1
gives the number of elements of typechar
that can fit the memory extent. It is evident thatsizeof( char )
is not greater thansizeof( int )
. So the same memory extent can accomodate more elements of typechar
than of typeint
. If for examplesizeof( int )
is equal to4
then the memory extent can accomodate5 * sizeof( int )
elements of typechar
that is20
.Each array element is an
int
and there are5
elements between both the pointers. Thus there will be5*sizeof(int)
amount of bytes in between both the pointers.Pointer arithmetics is always in the units of the base type.
In your case you have
Then doing
ptr1 + 5
will addsizeof(*ptr1) * 5
bytes to the pointerptr1
. Considering thatsizeof(*ptr1)
(which is the same assizeof(int)
) is4
, then you get4 * 5
which equals20
bytes.To quote
C11
, chapter §6.5.6, Additive operatorsSo, when you're doing
both
ptr1
andptr2
are pointers toint
, hence they are giving the difference in subscript, 5. In other words, the difference of the address is counted in reference to thesizeof(<type>)
.OTOH,
both
ptr1
andptr2
are casted to a pointer tochar
, 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.