prev

More Pointer Operations

next

The (ptr_a + 1) construct can be carried further with any of the C operators. (ptr_a + 6) represents an address for the 6th integer (24 bytes) from the current ptr_a value. Note, this doesn't actually have to be a valid value.

Similarly, ptr_a++ moves the pointer position forward one value and ptr_a-- moves the pointer backwards.
      /* ptr_a = the first value of the array */
      ptr_a = a;

      /* move forward, ptr_a = second value of the array */
      ptr_a++;

      /* jump forward two spots, ptr_a = fourth value of the array */
      ptr_a += 2;
    

A pointer to a function can also be passed around just like a pointer to a variable.

Source code
     #include <stdio.h>
     
     void numsort ( int *num1, int *num2, void (*)( int *, int * ) );
     void lessThan ( int *, int * );
     void greaterThan ( int *, int * );
     
     int main ( void ) {
       int i = 10,
           j = 3;
     
       /* sort the numbers so the smaller number is in i, the larger in j */
       numsort ( &i, &j, lessThan );
       printf ( "The smaller number is %d, the larger %d\n", i, j );
     
       /* sort the numbers so the larger number is in i, the smaller in j */
       numsort ( &i, &j, greaterThan );
       printf ( "The larger number is %d, the smaller %d\n", i, j );
     
       return ( 0 );
     }
     
     /*
      * does nothing more than call the compare function
      */
     void numsort ( int *num1, int *num2, void (*compare)( int *, int * ) ) {
       compare ( num1, num2 );
       return;
     }
     
     /*
      * rearranges the numbers so the smaller is in i and the larger in j
      */
     void lessThan ( int *i, int *j ) {
       int temp;
     
       if ( *i < *j )
         return;
         
       temp = *i;
       *i = *j;
       *j = temp; 
     
       return;
     }
     
     /*
      * rearranges the numbers so the larger is in i and the smaller in j
      */
     void greaterThan ( int *i, int *j ) {
       int temp;
     
       if ( *j < *i )
         return;
         
       temp = *j;
       *j = *i;
       *i = temp; 
     
       return;
     }


Output:
The smaller number is 3, the larger 10
The larger number is 10, the smaller 3