我正在尝试在C语言中实现树算法。我在一个独立的头文件(b_tree_ds.h)中声明了一个extern结构体。现在我计划在所有想要使用此结构体的源文件中导入该文件。因此,我必须在头文件中使用extern进行声明。
现在的问题是我也想定义它的typedef,但编译器报错说有多个存储类。我应该怎么做呢?
typedef extern struct node {
struct node* left;
struct node* right;
int key; // contains value
}NODE;
实际问题如下,但我仍然无法解决 ???
最近我学习了如何使用头文件和多个源文件使代码具有可移植性和分层性。为了做到这一点,我尝试使用这个原则来创建我的树程序。以下是我的文件:b_tree_ds.h - 这将包含一个树节点的数据结构的声明,可以调用不同功能实现树的各种函数(可能在不同的源文件中)
typedef struct node {
struct node* left;
struct node* right;
int key; // contains value
}NODE;
当我尝试像 typedef extern struct node
这样添加一个外部变量时,会出现多重存储类的错误,但如果我省略它,就会出现多重定义的错误。
这是我的其他源文件:
traverse.h - 包含 traverse 函数的声明。
void traverse_print (NODE* p);
在这里,我也遇到了未知标识符NODE的错误。
traverse.c - 包含该函数的定义。
#include <stdio.h>
#include "b_tree_ds.h"
#include "traverse.h"
void traverse_print(NODE* p)
{
if(p->left != NULL)
{
traverse_print(p->left);
}
if (p->right != NULL)
{
traverse_print(p->right);
}
printf ("\n%d",p->key);
}
最终的 main.c 文件
#include <stdio.h>
#include "traverse.h"
void main()
{
// input
NODE p;
printf("\nInput the tree");
input_tree (&p);
printf("\n\nThe tree is traversing ...\n")
traverse_print(&p);
}
void input_tree (NODE *p)
{
int in;
int c;
NODE *temp;
printf("\n Enter the key value for p: ");
scanf("%d", &in);
p->key =in;
printf ("\n\nIn relation to node with value %d",in);
printf ("Does it have left child (Y/N): ")
if ((c = getchar()) == Y);
{
//assign new memory to it.
temp = (NODE *)malloc(sizeof(NODE));
input_tree(temp);
}
printf ("\n\nIn relation to node with value %d",p->key);
printf ("\nDoes it have right child (Y/N): ")
if ((c = getchar()) == Y);
{
//assign new memory to it.
temp = (NODE *)malloc(sizeof(NODE));
input_tree(temp);
}
}
这是我第一次尝试这样的练习,请问我的程序结构是否良好,或者我应该尝试其他东西。