Thinking in C and *nix (CSC 295/282 2014S) : EBoards
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] [FAQ] [Teaching & Learning] - [Calendar]
Current: [Outline] [EBoard] [Lab] [Assignment]
Sections: [Assignments] [EBoards] [Examples] [Handouts] [Labs] [Outlines]
Reference: [EBook] - [ISO] [GNU Coding Standards] [GCC Documentation] - [TAoUP] [Make3]
Related Courses: [CSC 295 2013S]
Misc: [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] [Issue Tracker]
Overview
How do programmers use memory incorrectly?
Allocating space for a data type, and use the wrong amount of space.
double *d = malloc(2);
Run out of memory
Problems with freeing memory
You do it twice
int *ip = ...;
int *jp = ip;
...
free (ip);
free (jp);
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);
int strings_sort (int n, char strings[], int (compare)(char *, char *))
How do we pass in a function that meets this signature?
Just type the name of the function
strings_sort (10, names, strcmp);
int compare_by_length (char *str1, char *str2)
{
if (strlen(str1) > strlen(str2))
return 1;
else if (strlen(str1) < strlen(str2))
return -1;
else
return 0;
}
strings_sort (10, names, compare_by_length);
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
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] [FAQ] [Teaching & Learning] - [Calendar]
Current: [Outline] [EBoard] [Lab] [Assignment]
Sections: [Assignments] [EBoards] [Examples] [Handouts] [Labs] [Outlines]
Reference: [EBook] - [ISO] [GNU Coding Standards] [GCC Documentation] - [TAoUP] [Make3]
Related Courses: [CSC 295 2013S]
Misc: [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] [Issue Tracker]
Copyright (c) 2013-14 Samuel A. Rebelsky.

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.