/* Example 13.2: string comparison with pointers Source: K&R2, p106 Modified by Peter Brusilovsky Objective: use of pointers in processing character arrays */ #include #define MAXLEN 100 int strcmp(char *p1, char *p2); int getline(char *line, int max); main() { char a[MAXLEN], b[MAXLEN]; int comp; getline(a, MAXLEN); getline(b, MAXLEN); comp = strcmp(a, b); if(comp > 0) printf("First line is greater than second\n"); else if (comp < 0) printf("First line is less than second\n"); else printf("These lines are equal!\n"); } /* strcmp: return <0 if s0 if s>t */ int strcmp(char *s, char *t) { for( ; *s == *t; s++, t++) if(*s == '\0') return 0; return *s - *t; } /* getline: read a line into s, return length */ int getline(char *s, int lim) { int c, i; for (i = 0; i < lim-1 &&(c=getchar())!= EOF && c != '\n'; ++i) s[i] = c; if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; }