Thinking in C and *nix (CSC 295/282 2014S) : EBoards

CSC295 2014S, Class 12: Miscellaneous C Programming Issues


Overview

Preliminaries

Admin

Questions

Memory issues in C programs

Checking memory problems with valgrind

Sorting, revisited

Here's a standard signature

int strings_sort (int n, char *strings[]);

But wait! How do we specify what we want to sort by?

int strings_sort (int n, char *strings[], THING-TO-COMPARE-ELEMENTS compare);

Function pointers

int strings_sort (int n, char strings[], int (compare)(char *, char *))

How do we pass in a function that meets this signature?

Making the type name a bit easier

    typedef int (*StringComparator)(char *, char *);

    int strings_sort (int n, char *strings[], StringComparator compare);

Within out implementation of strings_sort, how do we call compare?

Really precise version

    (*compare)("alpha", "beta")

Normal C programmer version

    compare("alpha", "beta")

Challenge! Write a program that calls strings_sort to sort the strings on the command line alphabetically

    int 
    main (int argc, char *argv[])
    {
      int i;
      strings_sort (argc-1, argv+1, strcmp);
      for (i = 0; i < argc-1; i++)
        printf ("%s ", argv[i]);
      printf ("\n");
    } // main

Copyright (c) 2013-14 Samuel A. Rebelsky.

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.