Page 183 - C-Language
P. 183

Taking context pointers.




        A function pointer should almost always take a user-supplied void * as a context pointer.


        Example



         /* function minimiser, details unimportant */
         double findminimum( double (*fptr)(double x, double y, void *ctx), void *ctx)
         {
             ...
             /* repeatedly make calls like this */
             temp = (*fptr)(testx, testy, ctx);
         }

         /* the function we are minimising, sums two cubics */
         double *cubics(double x, double y, void *ctx)
         {
             double *coeffsx = ctx;
             double *coeffsy = coeffx + 4;

             return coeffsx[0] * x * x * x + coeffsx[1] * x * x + coeffsx[2] * x + coeffsx[3] +
                    coeffsy[0] * y * y * y + coeffsy[1] * y * y + coeffsy[2] * y + coeffsy[3];

         }

         void caller()
         {
             /* context, the coefficients of the cubics */
             double coeffs[8] = {1, 2, 3, 4, 5, 6, 7, 8};
             double min;

             min = findminimum(cubics, coeffs);
         }


        Using the context pointer means that the extra parameters do not need to be hard-coded into the
        function pointed to, or require the use globals.

        The library function qsort() does not follow this rule, and one can often get away without context
        for trivial comparison functions. But for anything more complicated, the context pointer becomes
        essential.




        See also



        Functions pointers


        Introduction


        Just like char and int, a function is a fundamental feature of C. As such, you can declare a pointer
        to one: which means that you can pass which function to call to another function to help it do its
        job. For example, if you had a graph() function that displayed a graph, you could pass which



        https://riptutorial.com/                                                                             159
   178   179   180   181   182   183   184   185   186   187   188