Aims and Objectives
Passing Arguments to a C Program
Calling C programs with multiple, optional Arguments
Pointers to Functions
Complicated Declarations
int argc /* argument count */ char *argv[] /* argument list */ /* e.g., echo hey "you in" there argc = 4 argv[0] = echo argv[1] = hey argv[2] = you in argv[3] = there argv[argc] = NULL */
#include <stdio.h> int main(int argc, char *argv[]) { while (--argc > 0) printf((argc > 1) ? "%s " : "%s", *++argv); printf("\n"); return 0; }
wc -l -c -w /* or */ wc -wl #include <stdio.h> main(int argc, char *argv[]) { int c, word = 0, line = 0, character = 0; int return_val = 1; while (--argc > 0 && (*++argv)[0] == '-') { while(c = *++argv[0]) { switch (c) { case 'w': word = 1; break; case 'l': line = 1; break; case 'c': character = 1; break; default: printf("wc: Illegal option %c\n", c); argc = 0; break; } } } if (argc != 0) printf("Usage: wc -l -c -w\n"); else {/* call function to count words, lines, characters count(*cs, *ws, *ls);*/ int cs = 1023, ws = 192, ls = 15; printf((character == 1) ? "chars = %d\n" : "", cs); printf((word == 1) ? "words = %d\n" : "", ws); printf((line == 1) ? "lines = %d\n" : "", ls); } }
#include <stdio.h> #include <string.h> #define MAXLINES 5000 char *lineptr[MAXLINES]; int readlines(char *lineptr[], int maxlines); int writelines(char *lineptr[], int nlines); void wsort(void *lineptr[], int left, int right, int (*comp)(void *, void *)); int numcmp(char *, char *); main(int argc, char *argv[]) { int nlines; int numeric = 0; /* 1 if numeric sort */ if (argc > 1 && strcmp(argv[1], "-n") == 0) numeric = 1; if ((nlines = readlines(lineptr, MAXLINES))>=0) { wsort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *))(numeric ? numcmp : strcmp)); writelines(lineptr, nlines); return 0; } else { printf("Input too big to sort\n"); return 1; } } void wsort(void *v[], int left, int right, int (*comp)(void *, void *)) { int i, last; void swap(void *v[], int, int); if (left >= right) return; swap(v, left, (left + right) / 2); last = left; for (i = left + 1; i <= right; i++) if ((*comp)(v[i], v[left]) < 0) swap(v, ++left, i); swap(v, left, last); wsort(v, left, last-1, comp); wsort(v, last+1, right, comp); }
int *f(); /* function returning pointer to int */ int (*f)(); /* pointer to function returning int */Some complicated declarations
char **argv argv: pointer to pointer to char int (*daytab)[13] daytab: pointer to array[13] of int int *daytab[13] daytab: array[13] of pointer to int void *comp() comp: function returning pointer to void void (*comp)() comp: pointer to function returning void char (*(*x())[])() x: function returning pointer to array[] of pointers to function returning char char (*(*x[3])())[5] x: array[3] of pointers to functions returning pointer to array[5] of char