-1
int vector[] = { 28, 41, 7 };
int *p0 = vector;
int *p1 = vector + 1;
int *p2 = vector + 2;

I know result of

printf("%p, %p, %p\n", p0, p1, p2);

is ex) 100, 104, 108

but why is the result of

printf("p2-p0: %d\n", p2 - p0);
printf("p2-p1: %d\n", p2 - p1);
printf("p0-p1: %d\n", p0 - p1);

is 2, 1, -1

not 8, 4, -4????????

PWS
  • 113
  • 4
  • Do you know what is the data type of the result of pointer difference? If you do, you should not use %d in printf... – machine_1 Feb 17 '19 at 13:55

1 Answers1

1

when you subtract to pointers (of the same type else no sense) that computes the difference as indexes, not the difference of the addresses :

type * p1 = ...;
type * p2 = ...;
(p1 - p2) == (((char *) p1) - ((char *) p2)) / sizeof(type)

It is the same when you do vector + n, that gives the address of the element rank n, not ((char *) vector) + n. So

type * p = ...;
int n = ...;

((char *) (p + n)) == (((char *) p) + n * sizeof(type))
bruno
  • 32,421
  • 7
  • 25
  • 37