该程序可以对输入的字符串进行排序,windows中以Ctrl+z结束。程序的思路是利用指针数组,指向存储在alloc函数分配的空间中的字符串,使用Qsort函数进行比较。在Qsort函数中,将key也就是待回归的值变为指针变量来存储指针数组中的地址,然后利用这个地址和其它指针数组中的地址传进strcmp函数中,来逐字比较字符串的大小,最后进行指针指向地址的交换。readline函数主要起一个读入输入的值以及为它们分配空间的作用,所以它包含alloc函数和getline函数,该函数最后返回读入字符串的行数。writeline函数主要起将指针数组指向的字符串输入的作用。afree函数在这个程序中并未使用,因为没有其它需要重新从头写入的操作,alloc函数的缺点就是分配空间的方式是一种假的晚绑定,不管是否使用该函数,它永远会占用空间,不过在目前,可以用于理解内存分配是如何进行的。
下面是代码段:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINE 100
#define MAXLEN 1000
char *lineptr[MAXLINE];
int readline(char **lineptr, int maxlines);
void writeline(char **pstr, int length);
void Qsort(char **pstr, int left, int right);
int main()
{
int nlines = 0;
if( (nlines = readline(lineptr, MAXLEN)) > 0)
{
Qsort(lineptr, 0, nlines - 1);
writeline(lineptr, nlines);
}
else
{
printf("none of sentence need sort");
}
return 0;
}
int getline(char *pstr, int length)
{
int c = 0;
int nIdx = 0;
while( (c = getchar()) != EOF && c != '\n' && nIdx < length)
{
pstr[nIdx++] = c;
}
if(c == '\n')
{
pstr[nIdx++] = '\n';
}
pstr[nIdx] = '\0';
return nIdx;
}
int readline(char **lineptr, int maxlines)
{
char *alloc(int nSize);
int len = 0;
int nlines = 0;
char *p = NULL;
char line[MAXLEN];
while( (len = getline(line, MAXLEN)) > 0)
{
if(nlines >= maxlines || (p = alloc(len)) == NULL)
{
return -1;
}
else
{
line[len - 1] = '\0'; //删除换行符
strcpy(p, line);
lineptr[nlines++] = p;
}
}
return nlines;
}
void writeline(char **pstr, int length)
{
int i = 0;
while(i < length)
{
printf("%s\n", *(pstr + i));
i++;
}
}
void Qsort(char **pstr, int left, int right)
{
if(left > right)
{
return;
}
int i = left;
int j = right;
char *key = pstr[left];
while(i < j)
{
while(i < j && strcmp(key, pstr[j]) <= 0)
{
j--;
}
pstr[i] = pstr[j];
while(i < j && strcmp(key, pstr[i]) >= 0)
{
i++;
}
pstr[j] = pstr[i];
}
pstr[i] = key;
Qsort(pstr, left, i - 1);
Qsort(pstr, i + 1, right);
}
#define ALLOCSIZE 100000
static char chAllocBuf[ALLOCSIZE];
static char *allocp = chAllocBuf;
char *alloc(int nSize)
{
if(allocp + nSize - chAllocBuf >= ALLOCSIZE)
{
return 0;
}
else
{
allocp += nSize;
return allocp - nSize;
}
}
void afree(char *pstr)
{
if(pstr >= chAllocBuf && pstr <= allocp)
{
allocp = pstr;
}
}