#include <stdio.h>
int main()
{
int a[5] = {1,2,3,4,5};
int *p = a;
int *q = p ;
int b = p-q;
printf("%d", b);
return 0;
}
p
is pointing on the 2
and q
is pointing to the 1
.
I know that Integer takes 4
bytes in the memory, so correct me if I am wrong, but for example if the address of a[0]
is 1000
, then the address of a[1]
will be 1004
if so, why does subtracting these addresses give us 1
and not 4
?
CodePudding user response:
Well, you have clearly misunderstood how pointer arithmetic works.
Consider this:
int a[5] = {1,2,3,4,5};
int *p = a;
p = p 1;
Now where do you expect p
to point? At 2
, i.e. at a[1]
? Or did you expect it to point in the middle of 1
, i.e. in the middle of a[0]
?
The answer is that p
points to a[1]
.
Now consider
int a[5] = {1,2,3,4,5};
int *p = a;
int *q = a;
p = p 1;
int b = p-q;
and do some simple substitution:
int b = p-q;
since
p is a 1
q = a
we get
int b = (a 1) - a;
which is
int b = 1;
So obviously the result is 1.
CodePudding user response:
From C11 Standard#6.5.6p9 [emphasis added]
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. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. ....
From this:
The subscript which specifies a single element of an array is simply an integer expression in square brackets.
int a[5] = {1,2,3,4,5};
int *p = a;
int *q = p ;
Both pointer p
and q
pointing to elements of same array object i.e. array a
. Pointer p
is pointing to second element of array a
, which is a[1]
(subscript is 1
) and pointer q
is pointing to first element of array a
, which is a[0]
(subscript is 0
).
The result of p - q
is 1 - 0
which is equal to 1
. Hence, you are getting output 1
.
Ideally, the type of b
should be ptrdiff_t
and provide %td
format specifier to printf()
for b
:
ptrdiff_t b = p - q;
printf("%td", b);