我是C的新手并试图编写一个程序来对char数组进行排序,方法是通过缩短指向它们的指针数组(一个程序,如D& K C编程语言pg-108)。这是我的代码 -
#include <stdio.h>
#include <string.h>
#define MAXLINES 5000
#define MAXLEN 100
char *line[MAXLINES];
int readlines(char *line[], int t);
void writelines(char *line[], int t);
void qsort(char *line[], int lo, int m);
int getline(char *, int);
char *alloc(int);
int partition(char *line[], int lo, int m);
int main()
{
int nlines; //no of input lines
if(nlines=readlines(line,MAXLINES)>=0)
{
qsort(line, 0, nlines-1);
writelines(line, nlines);
return 0;
}
else
{
printf("Error too many ");
return 1;
}
}
char store[10000]; //storage for alloc function
char *p = store;
char *alloc(int n) //next free position for allocating to the input lines
{
if (p + n <= store + 10000)
{
p += n;
return p - n;
}
else
return NULL;
}
int readlines(char *le[], int maxlines) //read the input lines to be sorted
{
char *p;
int i = 0;
char line[MAXLEN];
int len;
while ((len=getline(line,MAXLEN)) > 0)
{
if ((i >= maxlines)||((p = alloc(len)) == NULL))
{
return -1;
}
else
{
line[len - 1] = '\0';
le[i++] = p;
strcpy(p, line);
}
}
return i;
}
void writelines(char *line[], int t) /*function to print lines after
{ sorting */
for (int i = 0; i <= t - 1; i++)
printf("%s\n",line[i]);
}
int getline(char a[], int t) //function to read a line
{
int i = 0; //to count no of input char
int c;
while ((--t > 0) && (c = getchar()) != '\n'&&c != EOF)
a[i++] = c;
;
if (c== '\n')
a[i++]='\n';
a[i] = '\0';
return i;
}
void qsort(char *line[], int lo, int m) /*function to quick sort the pointer
{ array*/
if (lo >= m)
return;
int p = partition(line,lo,m);
qsort(line,p+1,m);
qsort(line,lo,p-1);
}
int partition(char *line[], int lo, int m) /*function for partition in
{ quick sort */
int index=0;
char *t = line[m];
for (int i = lo; i <= m - 1; i++)
{
if (strcmp(line[i], t) <= 0)
{
char *p = line[i];
line[i] = line[index];
line[index] = p;
index++;
}
}
char *p = line[m];
line[m] = line[index];
line[index] = p;
return index;
}
它由许多功能组成,我试图对每个功能进行排序描述。即使花了几个小时后我也无法弄清楚为什么它只打印第一个输入线。请帮助弄清楚是什么是这段代码中的问题。
答案 0 :(得分:0)
您需要替换:
if(nlines=readlines(line,MAXLINES)>=0)
...与
if((nlines=readlines(line,MAXLINES))>=0)