我如何发送另一个模块中的指针that's到一个新的模块?
你好,I'm刚开始在A类游戏下的编程Proyect。这个游戏包含了一个名为游戏结构也包含像玩家IR对象型动物类型的数据。这些结构是由一个长id标识,分类,以使对象具有一个Id之间#0和例如#100。
为了更方便了从来就创建函数“what_id”那recibing只是它返回一个指向对应它的结构的ID。我知道通过发送“游戏”结构,其中如何包含所有的ID和ID,返回的变量,但没有在任何情况下那么大“游戏”变量中使用,例如player.c there're模块。
我如何发送“游戏”这一功能,而无需呢?
typedef struct _Game{
Player* player[MAX_PLAYERS + 1];
Object* object[MAX_OBJECTS + 1];
Space* spaces[MAX_SPACES + 1];
T_Command last_cmd;
} Game;
typedef struct _Object{
Id id;
char name[MAX_SPACES];
}
void* what_id(Game* game, Id id){
if(id == NO_ID) return ERROR;
if(0 <id<=MAX_SPACES){
return what_space(game->space, id);
}else if(MAX_SPACES<id<=(MAX_OBJECTS+MAX_SPACES)){
return what_object(game->object, id);
}else if((MAX_OBJECTS+MAX_SPACES<id<(MAX_PLAYERS+MAX_OBJECTS+MAX_SPACES)){
return what_player(game->player, id);
}else {
fprinf(stderr,"Id asigment max stacked.";
return ERROR;
}
}
Space* what_space(const Space* space, Id id){
int i;
for(i=0;i<MAX_SPACES;i++){
if(space[i]->id == id)return space[i];
}
fprintf(stderr, "Error no space_id %d founded", id);
return ERROR;
}
目前尚不清楚你所说的“模块”的意思,或在游戏中从哪儿来。如果模块你的意思是产生独立的目标文件不同来源的文件,通常有两种方法可以做到这一点。
首先是声明一个全局变量并导入它作为一个extern:
file1.c中:
// declare struct
typedef struct {
int value;
} Foo;
// declare global variable
Foo *globalfoo;
// declare external function from another module
void printfoo();
void main()
{
Foo foo;
foo.value = 3;
globalfoo = &foo;
printfoo();
}
file2.c中:
#include <stdio.h>
// declare struct
typedef struct {
int value;
} Foo;
// declare variable from another module
extern Foo *globalfoo;
void printfoo()
{
printf("foo: %d\n", globalfoo->value);
}
另一种方式来做到这一点是通过一个函数参数传递给它:
file1.c中:
typedef struct {
int value;
} Foo;
void printfoo(Foo *foo);
void main()
{
Foo foo;
foo.value = 3;
printfoo(&foo);
}
file2.c中:
#include <stdio.h>
typedef struct {
int value;
} Foo;
void printfoo(Foo *foo)
{
printf("foo: %d\n", foo->value);
}
您可避免把它们放在一个头文件和#包括它再次宣布在多个源文件结构和功能:
myproject.h:
typedef struct {
int value;
} Foo;
void printfoo(Foo *foo);
file1.c中:
#include <myproject.h>
void main()
{
Foo foo;
foo.value = 3;
printfoo(&foo);
}
file2.c中:
#include <myproject.h>
#include <stdio.h>
void printfoo(Foo *foo)
{
printf("foo: %d\n", foo->value);
}