C-链表打印额外的链接



我的程序在开始时比我应该有的多打印了一个链接。我在调试中找不到问题。

此外,我不确定我的排序是否是最优的。

我已经添加了我正在测试的文本,我总共应该有26个链接,但我得到了27个。

NEWLY CHAINER READ ELEMENTS KAFKA YOUNG IS WELL SKILLED ZAPPED AT
PUBLISHED METAMORPHOSIS IMAGINE HIS A FRANCHISE WHEN WORLDWAR RAGEID VANQUISHED
TUBERCULOSIS XENOPHOBIA YET GREATLY ULTIMATELY 

我知道问题发生在init_and_sort_link((。

#include "stdio.h"
#include <stdlib.h>
#include <string.h>
const int FILEWORDNUMBER = 46;
struct link {
char *word;
struct link *next;
};
void init_and_sort_link(char **words, struct link *head) {
for (int i = 0; i < FILEWORDNUMBER; ++i) {
if (words[i] != 0) {
struct link *temp;
temp = head;
temp = malloc(sizeof(struct link));
temp->word = words[i];
temp->next = NULL;
if (strcmp(head->word, temp->word) < 0) {
temp->next = head;
} else {
struct link *cur = head;
while (cur->next != NULL &&
strcmp(temp->word, cur->next->word) >= 0) {
cur = cur->next;
}
temp->next = cur->next;
cur->next = temp;
}
}
}
}
void readLine(FILE *file, char **words) {
int i = 0;
char ligne[80];
while (fgets(ligne, 80, file)) {
char *word = strtok(ligne, " ,.-n");
while (word != NULL) {
words[(i)++] = strdup(word);
word = strtok(NULL, " ,.-n");
}
}
fclose(file);
}
int main(int argc, char *argv[]) {
FILE *file = fopen(argv[1], "r");
char **words = calloc(FILEWORDNUMBER, 30 * sizeof(char *) + 1);
readLine(file, words);
struct link *head = malloc(sizeof(struct link));
struct link *ptrr = head;
//head->word = words[0];
head->next = NULL;
init_and_sort_link(words, head);
int a = 0;
while (ptrr != NULL) {
printf("Link#%d ->%sn", a, ptrr->word);
ptrr = ptrr->next;
a++;
}
struct link *tmpp;
while (head != NULL) {
tmpp = head;
head = head->next;
free(tmpp);
}
for (int i = 0; i < FILEWORDNUMBER; ++i) {
free(words[i]);
}
free(words);
return 0;
}

好吧,这里有几个问题

第一个

Words是一个指向字符串的指针数组,因此必须像这样分配

char **words = calloc(FILEWORDNUMBER, sizeof(char *));

30*sizeof(char*) + 1)似乎是为了为字符串保留空间。还不需要。

第二个在init_and_sort_link中,我们有

struct link *temp;
temp = head;  <<<<=== this line is meaningless as its overwritten by the next line
temp = malloc(sizeof(struct link));
temp->word = words[i];
temp->next = NULL;
if (strcmp(head->word, temp->word) < 0) {

strcmp失败,因为头->这个词并没有被设定为任何东西。我不确定你在这里想要什么

我可以看到你注释掉了一行,这行本来会在主体中最小化head->word。我看到你的问题了,现在我把那条线放回

我会更改程序的结构,这样在调用int_sort之前就不会创建头。相反,在该函数中创建所有链接,并让它将头返回到main。

相关内容

  • 没有找到相关文章

最新更新