COP 4600 - Discussion 5

Introduction to C Programming - 4

Exercises

Every week at the end of discussion exercises will be given. You will have to submit them at the beginning of the next discussion on paper.

These may possibly count as bonus credit at the end of the semester, so try to do them.

  1. Exercise 1: Create these comparison functions:

    Createa a file called "mySort.h". Use conditional compilation to make sure that the file is not included twice in a project. (Update: Solution here. Test file )
    Create comparison functions for ints, floats and chars inside this header file. Prototype for all of them should be similar. Example:

    			// returns 1   - a > b
    			// returns 0   - a == b
    			// returns -1  - a < b
    			int compareInt(void* a, void* b); 
    			
  2. Exercise 2: Create a dispatch table:

    Create a dispatch table and a method which will return the proper comparison function depending on the type.
    The "commands" will be "int", "float" or "char". Method prototype:

    		int (*getDispatchPtr(char *comm))(void *a, void *b); 
    		
  3. Exercise 3: Create a selection sort method which uses the dispatch table:
    		void selectionSort(void *base, size_t nmemb, size_t size, char *command);
    		
    		// base = the array to sort
    		// nmemb = number of objects in the array
    		// size = sizeof of an object in the array
    		// command = the command which will tell the type...this will make the function look up the appropriate function pointer in the dispatch table.
    		
    		

Previous