将列表传输到班级

时间:2012-01-13 22:44:06

标签: c struct

我有一个检查点列表,然后运行一个函数。我最初在该函数中构建了这个列表,但现在我必须在外部构建它。问题是我无法在实现该函数的类中包含checkpoint.h,因为checkpoint.h返回该类型的结构。初始列表在class.c全局声明。如何将外部创建的列表转移到类中以便我可以使用它?

所以我有这个标题,turing_machine.h

#ifndef __TURING_MACHINE__ 
#define __TURING_MACHINE__

#include "tape.h"
#include "alphabet.h"
#include "symbol_table.h"

...

#endif

以及定义checkpoint.h类的checkpoint_list标头:

#ifndef __CHECKPOINT_H__
#define __CHECKPOINT_H__

#include "turing_machine.h"

...

#endif

所以我想从turing_machine.h发送一个结构列表checkpoint的函数,但我无法修改任何内容,因为这是类必须保留的方式。

我还有turing_machine.c

#include "turing_machine.h"
#include "checkpoint.h"
#include "symbol_table.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

checkpoint_list *c;

所以在开始时我在turing_machine中创建了列表c,但现在我必须在外面创建它,我必须初始化该列表c但我不知道如何。我希望这更清楚。

我使用了“错误”一词;我只有.c.h个文件。

1 个答案:

答案 0 :(得分:0)

在某些方面阅读,我认为你的麻烦在于你有'相互参照'的结构。

解决此问题的方法是使用不完整的类型定义:

typedef struct checkpoint_list checkpoint_list;

然后您可以在turing_machine.h

中使用它
#ifndef TURING_MACHINE_H_INCLUDED
#define TURING_MACHINE_H_INCLUDED

#include "tape.h"
#include "alphabet.h"
#include "symbol_table.h"

typedef struct checkpoint_list checkpoint_list;

typedef struct turing_machine
{
    ...
} turing_machine;

extern checkpoint_list *tm_function(turing_machine *);
extern turing_machine  *tm_create(const char *); 

#endif

而且,在checkpoint.h内,你可以写:

#ifndef CHECKPOINT_H_INCLUDED
#define CHECKPOINT_H_INCLUDED

#include "turing_machine.h"

/* No typedef here in checkpoint.h */
struct checkpoint_list
{
    ...
};

extern checkpoint_list *cp_function(const char *);
extern turing_machine  *cp_machine(checkpoint_list *);

#endif

该技术由C标准(C90,更不用说C99或C11)识别和定义。

请注意,我还重命名了包含警卫;以双下划线开头的名称是为'实现'(意思是C编译器及其库)保留的,你不应该在自己的代码中发明和使用这些名称。