《C程序设计语言》5.6指针数组以及指向指针的指针的例题 P93
#include
#include
#define MAXLINES 1000//最大文本行数
#define MAXLEN 100 //最大文本行字符数
#define ALLOCSIZE 100*1000
/*对文本行按字母顺序进行排序
当输入的文本行数大于最大文本行数时,及存放文本行的存储区不够时,
不能够对文本行进行排序处理。
*/
int readline(char *lineptr[]);
int getline(char *s, int max);
void sort(char *lineptr[], int);
void swap(char *s1, char *s2);
void writeline(char *lineptr[], int);
char *alloc(int );
int main()
{
char *lineptr[MAXLINES];
int nlines = 0;//文本行数
nlines = readline(lineptr);
if(nlines >= 0){
sort(lineptr, nlines);
writeline(lineptr, nlines);
}
else{
printf("write too more to sort!\n");
}
return 0;
}
//获取文本行
int readline(char *str[])
{
int nlines = 0, len;
char line[MAXLEN], *p;
while((len = getline(line, MAXLEN)) > 0){
if(nlines >= MAXLINES || (p = alloc(len)) == NULL){ //此处需要用到alloc函数,我的理解是,将需要排序的字符串先进行存储,然后再进行处理。
return -1;
}
else{
line[len-1] = '\0'; //此处需要将每个字符串后面的换行符去掉,我的理解是,去掉换行符有助于输出时的格式管理
strcpy(p, line); //此时将line中的字符串复制到p指向的存储区。 此处还要注意的是,将字符串复制到指针指向的存储区,要用strcpy(),而指针之间的地址赋值,直接用=就可以。
str[nlines++] = p; //注意标蓝色的地方,要先开辟出len个字符长度,然后将字符copy进去,之后再将p指针引。【这是我第二次自己再写时发现第一次写出后却没有理解的地方。】
}
}
return nlines;
}
//输入文本行内容,返回文本行长度
int getline(char *s, int max)
{
char c;
int i;
c = getchar();
for(i = 0; i < max && c != EOF && c != '\n'; i++)
{
s[i] = c;
c = getchar();
}
if(c == '\n'){
s[i++] = c;
}
s[i] = '\0';
return i;
}
//按字母大小比较文本行
void sort(char *lineptr[], int nlines)
{
int i, j;
for(i = 0; i < nlines-1; i++){
for(j = 1; j < nlines - 1 - i; j++){
if(strcmp(lineptr[j], lineptr[j+1]) > 0){
swap(lineptr[j], lineptr[j+1]);
printf("%s %s\n", lineptr[j], lineptr[j+1]);
}
}
}
}
//交换两个字符串的顺序
void swap(char *s1, char *s2)
{
char *p;
/*p = s1;
s1 = s2;
s2 = p;*/
strcpy(p, s1); //注意:字符串比较大小,用strcpy()函数,尽管此处是指针,也是用此函数比较
strcpy(s1, s2);
strcpy(s2, p);
}
//输出文本行
void writeline(char *lineptr[], int nlines)
{
int i = 0;
for(; i < nlines; i++)
printf("%s,", lineptr[i]);
}
//返回指向n个字符的指针
static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf;
char *alloc(int len)
{
if(allocbuf + ALLOCSIZE - allocp < len){
printf("the buf is not enough\n");
return NULL;
}
else
{
allocp += len;
return allocp - len;
}
}