Unusal Subtraction

please explain why this prints 3 instead of 12

1
2
int ptr[] = {1,2,23,6,5,6};
printf("%d",&ptr[3]-&ptr[0]);
Last edited on
Why should it print 12? First operand is third object from first, so it is logical to return 3.
This is how pointer arithmetics works: a - b = c such so b + c = a.
Other way to see is a simple math.
by standard:
1
2
ptr[3] == *(ptr + 3)
&ptr[3] == (ptr + 3)
so &ptr[0] == (ptr + 0) &ptr[3]-&ptr[0] == (ptr + 3) - (ptr + 0) == ptr - ptr + 3 - 0 == 3
@MiiNiPaa Thanks bro..I was thinking about address & as int is of 4 byte, I was thinking it to be 12...
int might be even 2 bytes long or bytes long, it is irrelevant.
Adding 1 to address of pointer of type X will give you address of next object of type X if this pointer pointed to array element.
To get the distance in bytes you must multiply theresult by sizeof(T), where T could be *ptr. For convenience, pointer distances are measured in elements, not bytes.
Topic archived. No new replies allowed.