按字母顺序排列的单词列表。我有一个指向每个单词的指针数组

Bubblesort list of words alphabetically. I have an array of pointers pointing to each word

所以我有一个程序接受一个列表并将它们放入指向每个单词的指针数组中。到目前为止,如果我只使用 get_lines 函数打印我程序的行部分,它会完美地打印 .txt 文件。我只需要帮助按字母顺序对这些单词进行冒泡排序,但我不确定如何进行。请帮忙!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int readfile(FILE*fp,char**cbuf);
char**get_lines(char *cbuf, int bufsize, int num_word);
int readword(FILE*tmp);
void sortA(char lines,int bufsize,int num_word);

int main(int argc, char*argv[])
{
  int i, bufsize, num_word;
  char*cbuf;
  char**lines;
  FILE*fp;
  FILE*tmp;
  FILE*outfile;
  char*newlines;

  outfile = fopen("words2.txt","w");
  if((fp=fopen(argv[1],"r"))== NULL)
    {perror("ERROR: bad/no filename");
      exit(0);
    }
  tmp = fopen(argv[1],"r"); 
  bufsize = readfile(fp,&cbuf);
  num_word = readword(tmp);
  lines = get_lines(cbuf,bufsize,num_word);
  i = 0;
  while(newlines[i] != NULL)
    {
      fprintf(outfile,"%s\n",newlines[i]);
      i++;
      }
  return 0;
}

int readfile(FILE*fp, char**cbuf)
{
  int i;
  char c;
  fseek(fp, 0L, SEEK_END);
  int bufsize = ftell(fp);
  fseek(fp, 0L, SEEK_SET);

  *cbuf = (char *)malloc(sizeof(char) * bufsize +1);
  for (i = 0; i < bufsize; i++)
    {
      c = fgetc(fp);
      (*cbuf)[i] = c;
    }
  return bufsize;
}

int readword(FILE*tmp)
{
  int word = 0;
  char c;

  while((c = fgetc(tmp)) != EOF )
    {
      if (c == '\n')
    word++;
    }
    return word;
}

char**get_lines(char*cbuf, int bufsize, int num_lines)
{
  char **lines = malloc((num_lines + 1) * sizeof *lines);

  int line = 0;
  while (line < num_lines)
    {
      lines[line++] = cbuf;
      cbuf = strchr(cbuf,'\n');

      if (!cbuf)
    break;

      *cbuf++ = '[=10=]';
    }
  lines[line] = NULL;

  return lines;
}

void SortA(char lines, int bufsize, int num_word)
{
  char t[bufsize];
  int i,j;


  for (i = 1; i < num_word; i++)
    {
      for (j = 1; j < num_word; j++)
    {
      if (strcmp(lines[j - 1], lines[j]) > 0)
        {
          strcpy(t, lines[j - 1]);
          strcpy(lines[j - 1], lines[j]);
          strcpy(lines[j],t);
        }
      }
    }

我在你的代码中发现了两个错误。第一个是在使用 argv[1] 之前不检查 argc。另一个是使用未初始化的 newlines,而不是 lines.

我还重写了 SortA() 并减少了参数。我纠正了循环,而不是交换字符串,我交换了指针。您不能 交换字符串 - 它们占用的字节数不同,并且它们按顺序位于您的缓冲区中。

...
void SortA(char **lines, int num_word);

int main(int argc, char*argv[])
{
    ...
    SortA(lines, num_word);
    i = 0;
    while(lines[i] != NULL)
    {
        fprintf(outfile,"%s\n",lines[i]);
        i++;
    }
    return 0;
}

void SortA(char **lines, int num_word)
{
    char *w;
    int i,j;
    for (i=0; i<num_word-1; i++)
    {
        for (j=i+1; j<num_word; j++)
        {
            if (strcmp(lines[i], lines[j]) > 0)
            {   
                w = lines[i];
                lines[i] = lines [j];
                lines[j] = w;
            }
        }
    }
}

输入文件:

one
two
three
four
five
six
seven
eight
nine
ten

输出文件:

eight
five
four
nine
one
seven
six
ten
three
two