繁体   English   中英

在结构中对char *进行排序-获取垃圾

[英]Sort char* in structs - getting garbage

我制作了一个Node结构数组,并试图根据它们的char *变量“ word”以字母顺序对节点进行排序。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "memwatch.h"
#include "concord.h"

#define BUFFSIZE 1000

int main(int argc, char** argv)
{
  Node** list;
  printf("%s%s\n","The file name is ",  argv[1]);
  readInputFile(argv[1], list);
  return 0;
}

int compareWords(const void* nodeA, const void* nodeB)
{
  Node* nodeAA = (Node *) nodeA;
  Node* nodeBB = (Node *) nodeB;
  puts("now here\n");
  printf("%s\n", nodeAA->word);
  printf("%s\n", nodeBB->word);
  return strcmp(nodeAA->word, nodeBB->word);
}

void readInputFile(char* filename, Node** wordList)
{
  FILE* file;
  file = fopen(filename, "r");
  wordList = calloc(BUFFSIZE, sizeof(Node*));

  char* currentWord;
  currentWord = (char*) malloc(sizeof(char) *BUFFSIZE);
  int i;
  i = 0;
  while(fscanf(file, "%s", currentWord)  == 1)
  {
    wordList[i] = (Node*) malloc(sizeof(Node));
    wordList[i]->word = strdup(currentWord);
    puts(wordList[i]->word);
  }
  fclose(file);
  qsort(wordList, i, sizeof(Node), compareWords);
}

在尝试在比较函数中打印单词时,在打印出垃圾之前,现在看来该函数甚至没有被调用。

现在看来该函数甚至没有被调用。

那是因为排序一个0元素的列表,您不需要比较两个元素:

  // ...
  int i;
  i = 0;    // --- set to 0
  while(fscanf(file, "%s", currentWord)  == 1)
  {
    // i not changed ... causes other problems, too
    // (contents omited)
  }
  fclose(file);
  // i is still 0
  qsort(wordList, i, sizeof(Node), compareWords);
  // ...

除此之外,正如David C. Rankin在评论中指出的那样,您对“输出参数”的使用是错误的。 在这种情况下,我也建议您仅使用返回值。

此外,我将该功能拆分为多个功能:

// Does the file opening and closing, calls readInput
Node * readInputFile(char const *);
// The actual reading
Node * readInput(FILE *)
// Probably do the sorting outside of these functions

[首先,您的问题不完整,因为它没有向我们展示Node的定义。]

但是,这里有三个问题:

  1. 我做了一个Node结构数组

    你不知道

    这里

     wordList = calloc(BUFFSIZE, sizeof(Node*)); 

    您可以为指向 Node指针数组分配内存。

    然后在这里

     wordList[i] = (Node*) malloc(sizeof(Node)); 

    您为先前创建的指针数组的每个元素分配了单独的内存块。

    后者可能分散在整个进程的内存中。 它们将不会位于qsort()所期望的连续内存块中,这可能是以下原因:

    我正在打印垃圾[之前]

  2. readInputFile()返回时, wordList的值将丢失。

  3. 读取循环不会使索引计数器i递增。


要修复1.和2.,请创建一个数组,然后readInputFile()它的引用返回给readInputFile()的调用者, readInputFile()

*wordList = calloc(BUFFSIZE, sizeof **wordList);

然后像这样调用qsort()

qsort(*wordList, i, sizeof(Node), compareWords);

要解决3.请执行以下操作:

size_t i = 0; /* No need for negative indexes here .*/
while((i < BUFFSIZE) /* Male sure not to overflow the array. */   
      && (fscanf(file, "%s", currentWord) == 1))
{
  (*wordList)[i].word = strdup(currentWord); /* This is POSIX not Standard C. */
  puts((*wordList)[i].word);
  ++i;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM