识别C头文件中的结构

问题描述

我正在尝试使用哈希表创建字典,因此我创建了一个名为node的结构,该结构具有一个与其关联的word一个next指针:

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// Hash table
struct node *table[5];

main中,我初始化了一个node,现在正尝试将其加载到哈希表中:

void hash_insert_node(struct node **hash_table,struct node *n,int value)
{
    hash_table[value] = n;
    printf("%s\n",hash_table[value]->word);
}

我在名为dictionaries.h文件中有此功能的原型,而在名为dictionaries.c文件中有此代码。在dictionaries.c的顶部,我有

#include "dictionaries.h"

如果我现在运行代码,则会出现以下错误

declaration of 'struct node' will not be visible outside of this function 
[-Werror,-Wvisibility]

我发现解决此问题的唯一方法是将结构的定义移至dictionaries.h,但这似乎很愚蠢。

这可能是一个琐碎的问题,但我将不胜感激。

解决方法

我发现解决此问题的唯一方法是将结构的定义移至dictionaries.h,但这似乎很愚蠢。

对我来说,这似乎并不愚蠢,@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Uri data = intent.getData(); webView.loadUrl(data.toString()); } 文件似乎是放置.h声明的理想场所。


出现问题是因为您的函数不知道struct的存在。

您可以通过一些不同的方式解决此问题:

  1. Forward declare the struct在函数之前的声明:
struct
  1. struct node; char *GetHashWord(struct node **hash_table,int value); 放在一个单独的struct文件中,您可以命名该文件,例如.h,并在data_structure.h中将其#include命名。
  2. 保留您的原始修复程序,我认为没有理由将其视为不良做法。

顺便提一下,如果您要为结构命名,您也可以使用它:

dictionaries.h
,

通常,如果您要创建一个数据结构,并希望从用户那里抽象出该数据结构,则无需用户知道其自身包含的结构变量。 如果您想知道哈希表中的单词,则应在定义结构的.c文件中编写一个getter函数,并将此函数的声明包括在.h文件中。 .c文件中的函数实现的示例。

char *GetHashWord(struct node **hash_table,int value)
{
   return hash_table[value]->word;
}

清白的例子:

char *GetHashWord(struct node **hash_table,int value);

这样,用户将不知道您如何实现该结构,并且能够包括一个抽象级别,并且仍然可以根据需要提供您希望他访问的变量。