gpt4 book ai didi

C:创建索引,我做错了什么?

转载 作者:行者123 更新时间:2023-12-03 03:43:48 24 4
gpt4 key购买 nike

我创建了下一个索引代码:

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

struct wordlist {
char *value;
int *lines;
struct wordlist *next;
};

int compare (struct wordlist *one , struct wordlist *two) {
return strcmp(one->value, two->value);
}

void add(struct wordlist **pp, char *value, int line) {

struct wordlist *new;
new = malloc(sizeof(*new));
new->value = value;

for ( ; *pp != NULL; pp = &(*pp)->next) {
if (compare(*pp, new) == 0) {
return;
}
else if (compare(*pp, new) > 0) {
break;
}
}

new->next = *pp;
*pp = new;
}

void display(struct wordlist *ptr) {

for (; ptr != NULL; ptr = ptr->next) {
printf("%s\n", ptr->value);
}
}

代码太多了所以我打破它来提交。抱歉

int main(void) {
struct wordlist *root = NULL;
int c;
char *word;
word = malloc(sizeof(char*));
int line = 1;
for (int i = 0;;i++) {
c = getchar();
if (c == EOF) {
break;
}
if (!isalpha(c)) {
i = -1;
add(&root, word, line);
word = malloc(sizeof(char));
if (c == '\n') {
line++;
}
continue;
}
c = tolower(c);
word[i] = c;
word = realloc(word,(i+1)*sizeof(char));
}
display(root);

return 0;
}

它假设用不是 a-z 或 A-Z 字符的所有内容来破坏字符串。

当我通过给他一个像这样的字符串来调试我的代码时

yonatan.lif

他正在打印:

lif yonatanp

我的输出应该是

lif yonatan

(我不希望出现“p”或任何其他字符)

只要输入的是不应该出现的字符串后面的字符长度较长的

它有效,但它按照我在长输入中描述的方式运行,我不明白为什么。你能帮我弄清楚我做错了什么吗?

感谢所有帮助者。

最佳答案

当您使用大多数标准头文件提供的函数(例如 strcmp())时,C 中的字符串必须以 null 结尾printf() 等等。来自 strcmp()引用文献:

This function starts comparing the first character of each string. [...] it continues [...] until a terminating null-character is reached.

这就是导致您调用的未定义行为的原因,但不是 null 终止您的字符串。为此,请将代码修改为:

word[i] = '\0';
i = -1;
add(&root, word, line);

现在您的单词将以 null 终止,您的程序将正常运行。

<小时/>

这是您的程序所发生情况的场景(应该拿一张纸和一支铅笔画出您的代码下次执行的操作)。

  1. word 指向“yonatan”。
  2. 您输入了“.”,因此调用了 add()
  3. 创建了一个new结构,它的下一个成员将在其中设置为root,即NULLvalueword指向的位置,和 line...好吧,这个成员将保持未初始化状态(它应该可能会被设置为 0,但你更清楚)。
  4. 我们继续,现在 word 忘记了“yonatan”并指向“生命”。
  5. add() 再次被调用,其中创建了另一个 new 结构体,其中其为“lif”,其下一个为先前创建的struct,在第 3 步。这就是为什么你的单词将被保留打印从他们的输入顺序。 line 将再次保持未初始化状态。
  6. display() 被调用,但 %s 格式寻找 null要停止的终止符,您的字符串可能缺少终止符,因此调用未定义的行为(您正在目睹的垃圾字符,例如'p')。

现在您应该问我的 for 循环和 compare() 函数怎么样?一旦第二次调用 add() 并调用 compare() 函数,您将进入该循环,但没有以 null 结尾的字符串 strcmp() 未能正确完成其工作,我的猜测是它返回了一个垃圾正值,从而破坏了循环。

<小时/>

PS:不是问题,但可能会给读者带来困惑:

char *word;
word = malloc(sizeof(char*));

为什么要为指针分配空间?您可能只想这样做:

word = malloc(sizeof(char));

关于C:创建索引,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43641971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com