Page 170 - C-Language
P. 170

Pre-Standard History:



        Prior to C89 during K&R-C times there was no type void* (nor header <stdlib.h>, nor prototypes,
        and hence no int main(void) notation), so the pointer was cast to long unsigned int and printed
        using the lx length modifier/conversion specifier.

        The example below is just for informational purpose. Nowadays this is invalid code, which
        very well might provoke the infamous Undefined Behaviour.


         #include <stdio.h> /* optional in pre-standard C - for printf() */

         int main()
         {
           int  i;
           int *p = &i;

           printf("The address of i is 0x%lx.\n", (long unsigned) p);

           return 0;
         }


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


                                                                                          *1
        Subtracting the values of two pointers to an object results in a signed integer  . So it would be
        printed using at least the d conversion specifier.


        To make sure there is a type being wide enough to hold such a "pointer-difference", since C99
        <stddef.h> defines the type ptrdiff_t. To print a ptrdiff_t use the t length modifier.


        C99

         #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



        https://riptutorial.com/                                                                             146
   165   166   167   168   169   170   171   172   173   174   175