gpt4 book ai didi

c - strtok(我想)错误我无法理解

转载 作者:行者123 更新时间:2023-12-02 21:42:37 25 4
gpt4 key购买 nike

编辑:复制行为的最小编译代码。

此代码读取一个蹩脚的字典文件,以便尝试从中提取一些有趣的信息。每一行都转换为一个结构条目。总是提取单词,因此 newentry() 不会检查其单词参数的有效性。

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

typedef struct entry {
char *word;
char *cat;
char *gen;
} entry;

entry *newentry(char *word, char *cat, char *gen) {
entry *w = malloc(sizeof(entry));
w->word = malloc(sizeof(strlen(word)) + 1);
strcpy(w->word, word);
if (cat) {
w->cat = malloc(sizeof(strlen(cat)) + 1);
strcpy(w->cat, cat);
}
else {
w->cat = "";
}
if (gen) {
w->gen = malloc(sizeof(strlen(gen)) + 1);
strcpy(w->gen, gen);
}
else {
w->gen = "";
}
return w;
}


int main() {
FILE *original = fopen("French.txt", "r");
char *line = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&line, &len, original)) != -1) {
char *word = strtok(strdup(line), "\t");
char *tmp = strtok(NULL, "[\n");
char *cat = strtok(NULL, "]\n");
newentry(word, cat, tmp); //bugs here
}
return 0;
}

这段代码在它的行(代码)行上失败了,我完全不知道为什么。如果我用单词、cat 或常量替换 tmp,它每次都会起作用。如果我要更改 newentry() 参数的顺序,只要 tmp 是一个参数,它每次都会失败。我当时尝试通过中断来调试。正在解析的文件大约有 4000 行,所以我想象某些行(这是一个非常蹩脚的文件)以某种方式损坏了,我尝试继续 1000,并得到一个异常。所以我重新启动并尝试了其他的 continue 值 - 但通过执行 continue 100 11 次,我能够超过之前的 1000。

我的结论是 tmp 被以下 strtok 不知何故损坏了。因此我尝试了char *tmp = strdup(strtok(NULL, "[\n"));而且效果并没有更好。

用 printf("%s %s %s", word, tmp, cat) 替换 newentry() 失败的行;尽管我无法通过肉眼检查 4000 个值,但 100% 的情况下都有效。

我真的不知道如何摆脱这种困惑,并且希望得到任何指点。

编辑:数据文件中的几行:

courthouse  palais de justice[Noun]
courtier courtisan[Noun]
courtliness e/le/gance[Adjective]
courtly e/le/gant[Adjective]
courtmartial conseil de guerre[Noun]
courtroom salle d'audience[Noun]

谢谢。

整个输入文件,以防有人真的好奇:http://pastebin.com/VPp8WpuK

最佳答案

这是错误的:

entry *w = malloc(sizeof(entry *));

你想要:

entry *w = malloc( sizeof *w );

或者:

entry *w = malloc( sizeof( entry ))

关于c - strtok(我想)错误我无法理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20099121/

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