gpt4 book ai didi

使用头文件时 C 程序不编译

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:15:17 25 4
gpt4 key购买 nike

(C 程序)我正在尝试编译一个使用 header 的 main.c,但出现以下错误。当我不使用 header (主文件中的所有方法)时,一切正常。

在字符串 S 中,程序查找所有出现的单词并返回出现次数最多的单词。

我正在编译使用:gcc main.c

谢谢。

错误

In file included from main.c:9:0:
frequence.h:4:16: warning: useless storage class specifier in empty declaration [enabled by default]
main.c: In function ‘main’:
main.c:15:10: error: variable ‘word’ has initializer but incomplete type
main.c:15:10: warning: passing argument 1 of ‘show_all_words’ from incompatible pointer type [enabled by default]
frequence.h:6:17: note: expected ‘char *’ but argument is of type ‘char (*)[34]’
main.c:15:10: error: invalid use of undefined type ‘struct stat_mot’
main.c:15:19: error: storage size of ‘word’ isn’t known

ma​​in.c

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

#define LONGUEURMAX 4

int main(char *argv[]) {
char texte[] = ";! one two, tree foor one two !:;";
struct stat_mot word = show_all_words(&texte);

printf("%s : %d\n", word.word, word.frequency);

return (EXIT_SUCCESS);
};

频率.h

#ifndef DEF_FREQUENCE
#define DEF_FREQUENCE

typedef struct stat_mot;
int count_word(char * , char * );
struct stat_mot show_all_words(char *);

#endif

频率.c

#include "frequence.h"

typedef struct stat_mot {
char * word;
int frequency;
} stat_mot;

int count_word(char * mot, char * text) {
int n = 0;
char *p;

p = strstr(text, mot);
while (p != NULL) {
n++;
p = strstr(p + 1, mot);
}

return n;
}

stat_mot show_all_words(char * text) {
char * text_rw = strdup(text);
char * p = strtok(text_rw, " .,;:-!?");

char word_to_return[strlen(text)];
int word_frequence = 0;

while (p != NULL) {
if (strlen(p) >= 0) {
int offset = p - text;
int count = count_word(p, text);

if (word_frequence < count) {
strcpy(word_to_return, p);
word_frequence = count;
}
};

p = strtok(NULL, " .,;:-!?");
}

free(text_rw);
struct stat_mot word = { word_to_return, word_frequence };
return word;
}

最佳答案

至少,您需要将 stat_mot 的定义从 frequence.c 移动到 frequence.h。 main() 尝试创建它的一个实例,如果没有结构定义,你不能这样做。

还有一些其他问题:

  • 我很难相信 char*char(*)[34] 之间的类型不匹配可以通过将所有内容放入一个文件来解决。所以我希望修复与您将代码组织到文件中无关,只是您应该传递 texte,而不是 &texte
  • “空声明中无用的存储类说明符”——这是一个令人困惑的错误消息,但它的出现是因为在 C 语法中 typedef 是一个存储类说明符。不要问为什么。基本上,typedef struct stat_mot; 是错误的,但这没关系,因为您可以在移动结构定义时删除它。

关于使用头文件时 C 程序不编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12839314/

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