Printing the Difference of the Values of two Pointers to an Object

suggest change

Subtracting two pointers into the same array yields a signed integer of type ptrdiff_t (since C99, in <stddef.h>). Print it with the t length modifier and a d conversion, %td. The subtraction is undefined behavior if the pointers do not address elements of the same array, or one past its end.

#include <stdlib.h> /* for EXIT_SUCCESS */
#include <stdio.h> /* for printf() */
#include <stddef.h> /* for ptrdiff_t */
int main(void)
{
  int a[2];
  int * p1 = &a[0], * p2 = &a[1];
  ptrdiff_t pd = p2 - p1;

  printf("p1 = %p\n", (void*) p1);
  printf("p2 = %p\n", (void*) p2);
  printf("p2 - p1 = %td\n", pd);

  return EXIT_SUCCESS;
}

The result might look like this:

p1 = 0x7fff6679f430
p2 = 0x7fff6679f434
p2 - p1 = 1

The difference counts elements, not bytes. Here the pointers address adjacent int elements, so the printed difference is 1. In the sample addresses, those elements are 4 bytes apart, which means sizeof(int) was 4 on that run.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents