-1

the following C program


#include <stdio.h>
#include <stddef.h>

#define A 1
#define B 1

int main(){
    int a[A], b[B];
    ptrdiff_t delta;


    printf("%p    %p",&a+A,&b);
    delta=&a+A-&b;
    printf("\n* %td *\n",delta);

    if ((&a+A)==&b) printf("\n==1.1");
    if ((&a+A)-&b==0) printf("\n==1.2");
    if (&a==&a) printf("\n==2");

    return 0;
}

produces this result:

0x7fff107d5454    0x7fff107d5440
* 5 *

==2

Can you explain me ehy 0x7fff107d5454-0x7fff107d5440=5?

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • 1
    `&a` is a `int (*)[A]`, i.e., a pointer to array of size `A`, not a pointer to int. Arrays decay to a pointer to their first element, so `a + A` or `&a[0] + A` are equivalent and would increment by `A * sizeof(int)`. – Ed S. Apr 07 '14 at 18:22
  • possible duplicate of [Pointer subtraction confusion](http://stackoverflow.com/questions/3238482/pointer-subtraction-confusion) – Carl Norum Apr 07 '14 at 18:34

1 Answers1

2

This is pointer arithmetic. Strictly, 0x7fff107d5454 - 0x7fff107d5440 is 0x14, which is 20 decimal. In pointer arithmetic the actual difference is divided by the sizeof the base pointer type, which is in this case 4 for integers (on your system). So you get 5.

perreal
  • 94,503
  • 21
  • 155
  • 181