[英]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
的定義。]
但是,這里有三個問題:
我做了一個Node結構數組
你不知道
這里
wordList = calloc(BUFFSIZE, sizeof(Node*));
您可以為指向 Node
的指針數組分配內存。
然后在這里
wordList[i] = (Node*) malloc(sizeof(Node));
您為先前創建的指針數組的每個元素分配了單獨的內存塊。
后者可能分散在整個進程的內存中。 它們將不會位於qsort()
所期望的連續內存塊中,這可能是以下原因:
我正在打印垃圾[之前]
從readInputFile()
返回時, wordList
的值將丟失。
讀取循環不會使索引計數器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.