5.2 指针与函数参数
#include <stdio.h> #include <stdlib.h> #include <ctype.h> int getch(void); void ungetch(int); /*getint 函数:将输入中的下一个整型数赋值给*pn */ int getint(int* pn) { int c, sign; while (isspace(c = getch())) /*跳过空白符*/ ; if (!isdigit(c) && c != EOF && c != '+' && c != '-') { ungetch(c); /*输入不是一个数字 */ return 0; } sign = (c == '-') ? -1 : 1; if (c == '+' || c == '-') c = getch(); for (*pn = 0; isdigit(c); c = getch()) * pn = 10 * *pn + (c - '0'); *pn *= sign; if (c != EOF) ungetch(c); return c; } #define BUFSIZE 100 char buf[BUFSIZE]; int bufp = 0; int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } void ungetch(int c) { if (bufp >= BUFSIZE) printf("ungetch: too many characters "); else buf[bufp++] = c; } int main() { int n, array[10]; for (n = 0; n < 10 && getint(&array[n]) != EOF; n++) ; for (n = 0; n < 10; n++) printf("%d ", array[n]); return 0; }
5.6 指针数组以及指向指针的指针
#include <stdio.h> #include <string.h> #include <stdio.h> #define MAXLINES 5000 /*最多可以输入5000行*/ #define MAXLEN 1000 /*max length of any input line*/ #define ALLOCSIZE 10000 /*size of available space */ char *lineptr[MAXLINES]; /*指向所有行的指针*/ static char allocbuf[ALLOCSIZE]; /*storage for alloc*/ static char *allocp = allocbuf; /*next free position */ int readlines(char *lineptr[], int nlines); void writelines(char *lineptr[], int nlines); int add_getline(char *, int); char *alloc(int); void qsort(char *lineptr[], int left, int right); /* sort input lines*/ int main() { int nlines; /*number of input lines read*/ if ((nlines = readlines(lineptr, MAXLINES)) > 0) { qsort(lineptr, 0, nlines - 1); writelines(lineptr, nlines); return 0; } else{ printf(" error : input too big to sort "); return 1; } } /*readlines : read input lines*/ int readlines(char *lineptr[], int maxlines) { int len, nlines; char *p, line[MAXLEN]; nlines = 0; printf("please input the strings need to sort "); while ((len = add_getline(line, MAXLEN)) > 0) { if (nlines >= maxlines || (p = alloc(len)) == NULL) { return -1; } else{ line[len - 1] = '