c - 如何从指针到指针引用变量的值?

标签 c variables pointers struct compiler-errors

我有一个结构:

 struct room;
 ...
 /*some more structs */

 typedef struct {     
   int state;
   int id;
   struct room* north;
   struct room* south;
   struct room* east;
   struct room* west;
   creature* creatures[10];
 } room;

还有一个打印内容的函数:

 void printContentsOfRoom(room* r) {
   printf("\nRoom %d:\n", r->id);
   printf("\tState: %s\n", getState(r));
   printf("\n\tNeighbors:\n");
   if (r->north.id != -1)
     printf("\t    North: Room %d\n",((room*)r->north)->id);
   if (r->east.id != -1)
     printf("\t    East: Room %d\n",((room*)r->east)->id);
   if (r->south.id != -1)
     printf("\t    South: Room %d\n",((room*)r->south)->id);
   if (r->west.id != -1)
     printf("\t    West: Room %d\n",((room*)r->west)->id);
   printf("\n\tCreatures:\n");
   for (int i = 0; i < 10; i++) {
     creature* c = (creature*)r->creatures[i];
     if (c) {
       if (c == pc)
     printf("\t    %s\n",getType(c));
       else
     printf("\t    %s %d\n",getType(c),c->id);
     }
   }
 }

我试图将房间 ID 设置为 -1(在程序运行时设置),它不会打印有关该房间的信息。编译时,我收到错误“请求非结构或 union 中的成员‘id’。”

此外,我尝试设置 if 条件 r->north->id,并返回错误“取消引用指向不完整类型'struct room'的指针”

最佳答案

我认为你想要做这样的前向声明:

typedef struct room room;

struct room{
    .
    .
    .
};

然后你可以使用r->north->id。看到这个问题:How to define a typedef struct containing pointers to itself?

关于c - 如何从指针到指针引用变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39693707/

相关文章:

计算输入。

c++ - Photoshop如何将两张图片融合在一起?

javascript - 使用字符串作为变量名称

c++ - 为什么*ptr在printf中?

c++ - 为什么基于指针交换两个值在函数范围之外不起作用?

C 在一个头文件中定义枚举并在另一个文件中使用该枚举作为函数参数

c - 如何找到从一个节点开始的所有简单路径?

r - 我如何在 R 中创建这个变量?

variables - Get-ADuser:无法识别搜索过滤器

c - 如何在C中将数组A的指针设置为指向数组B