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

时间:2015-03-17 19:03:11

标签: c arrays string pointers bubble-sort

所以我有一个程序,它接受一个列表并将它们放入指向每个单词的指针数组中。到目前为止,如果我只使用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++ = '\0';
    }
  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);
        }
      }
    }

1 个答案:

答案 0 :(得分:1)

我在你的代码中发现了两个错误。第一个是在使用argc之前未检查argv[1]。另一个是使用未初始化的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