5.6.指针数组以及指向指针的指针 —– 文本排序
#include <stdio.h>
#include <string.h>
#define MAXLINES 5000 /* max #lines to be sorted */
char *lineptr[MAXLINES]; /* pointers to text lines */
int readlines(char *s[], int nlines);
void writelines(char *s[], int nlines);
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\n");
return 1;
}
}
#define MAXLEN 100
int getlines(char *s, int lim);
char *alloc(int n);
/* readlines: read input lines */
int readlines(char *lineptr[], int maxlines)
{
int len, nlines = 0;
char line[MAXLEN], *p;
while((len = getlines(line, MAXLEN)) > 0){
if(len >= maxlines || (p = alloc(len)) == NULL)
return -1;
else {
line[len-1] = '\0';
strcpy(p, line);
lineptr[nlines++] = p;
}
}
return nlines;
}
/* writelines: write output lines */
void writelines(char *lineptr[], int nlines)
{
while(nlines-- > 0)
printf("%s\n", *lineptr++);
}
/* read a line, return length */
int getlines(char *p, int lim)
{
int c, i = 0;
while(i < lim-1 && (c = getchar()) != EOF && c != '\n'){
p[i++] = c;
}
if(c == '\n')
p[i++] = c;
p[i] = '\0';
return i;
}
/* sort v[left] ... v[right] into increasing order */
void qsort(char *v[], int left, int right)
{
int last, i;
void swap(char *[], int, int);
if(left >= right )
return;
swap(v, left, (left+right)/2);
last = left;
for(i = left+1; i <= right; i++ )
if(strcmp(v[left], v[i]) > 0)
swap(v, ++last, i);
swap(v, last, left);
qsort(v, left, last-1);
qsort(v, last+1, right);
}
void swap(char *v[], int i, int j)
{
char *p;
p = v[i];
v[i] = v[j];
v[j] = p;
}
#define ALLOCSIZE 10000 /* size of available space */
static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf;
char *alloc(int n) /* return pointer to n characters */
{
if(allocbuf + ALLOCSIZE - allocp >= n){
allocp += n;
return allocp - n;
} else /* not enough room */
return 0;
}
day_of_year & month_day exchange
#include <stdio.h>
static char daytab[2][13] = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
int day_of_year(int, int, int);
void month_day(int, int, int *, int *);
int main()
{
printf("%d,", day_of_year(2015, 8, 24));
int pmonth;
int pday;
month_day(2015, 236, &pmonth, &pday);
printf("%d-%d\n", pmonth, pday);
return 0;
}
/* day_of_year: set day of year from month & day */
int day_of_year(int year, int month, int day)
{
int leap, i;
leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
for(i = 1; i < month; i++)
day += daytab[leap][i];
return day;
}
/* month_day: set month, day from yearday */
void month_day(int year, int yearday, int *pmonth, int *pday)
{
int i, leap;
leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
for(i = 1; yearday > daytab[leap][i]; i++)
yearday -= daytab[leap][i];
*pmonth = i;
*pday = yearday;
}
结果:
236,8-24