Search code examples
c++carrayspointersstrchr

Subtracting char array from char pointer produces an int?


In the strchr reference at http://www.cplusplus.com/reference/cstring/strchr/, this example is provided.

/* strchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  printf ("Looking for the 's' character in \"%s\"...\n",str);
  pch=strchr(str,'s');
  while (pch!=NULL)
  {
    printf ("found at %d\n",pch-str+1);
    pch=strchr(pch+1,'s');
  }
  return 0;
}

Why does subtracting the char array str from the char pointer pch plus one give an int? (as denoted by the %d format type) If I remove "-str", the program wouldn't execute until I change %d to %s.


Solution

  • The short of it is, that's a bug:
    That expression might be of type int, or you might have Undefined Behavior in the call to printf.

    Let's take it step by step:

    1. You are not actually subtracting an array from a pointer, but a pointer from a pointer:
      In nearly all contexts, an array decays to a pointer to its first element.

    2. What type is the difference of two pointers (which is only defined if they point at or directly behind elements from the same array)?

      ptrdiff_t (That's what that typedef in <stddef.h> is for.)

    3. ptrdiff_t might happen to be int, but don't depend on it.
      Instead, use the proper format-specifier: %ti.