gpt4 book ai didi

c - 如何创建外部结构并定义其 typedef

转载 作者:太空狗 更新时间:2023-10-29 16:30:05 24 4
gpt4 key购买 nike

我试图在 C 中实现树算法。我在一个完全独立的头文件 (b_tree_ds.h) 中声明了一个外部结构。现在我打算在所有要使用此结构的源文件中导入该文件。所以我必须在 header 中使用 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 中添加一个 extern 时,它给出了多个存储类的错误,但如果我错过了它,我会得到多个定义的错误。

这是我的其他源文件

traverse.h - 包含遍历函数的声明

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);
}
}

这是我第一次尝试这种做法,请建议我的程序结构是否合适,或者我应该尝试其他方法。

最佳答案

你不能创建结构extern。只需在包含防护保护的 header 中定义它,并将该 header 包含在您需要的任何地方。

编辑 SquareRootOfTwentyThree

我在 the following way 中使用了那些热量:

A structure type definition describes the members that are part of thestructure. It contains the struct keyword followed by an optionalidentifier (the structure tag) and a brace-enclosed list of members.

A structure declaration has the same form as a structure definitionexcept the declaration does not have a brace-enclosed list of members.

所以“定义”正是我的意思。

关于c - 如何创建外部结构并定义其 typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9749943/

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