c - 如何访问作为指针确定的结构体的结构体成员?

标签 c struct

我正在尝试用c语言创建一个潜艇游戏,所以我制作了一个结构,将棋盘上潜艇的“位置”连接到潜艇本身,这些是我使用的结构;

struct Point_s
{
    int x;
    int y;
};

struct BoardPart_s
{
    boolean ishit;//yes = 1 no = 0
    Submarine* Sub;
};

   struct Submarine_s
{
    Point start;
    Point end;
    int Life;// this is calculated from the diffrence of the non equal part of the x/y Point
};

现在当这样分配时

Board[xstart][yend]->Sub=&(Plist->sub);// plist is a linked list conatining a submarine

但是当我尝试像这样访问其成员(member)生活时

   BoardPart BoardP2[BoardSize][BoardSize];// boardsize is 10
.
.
.
.
.
if( BoardP2[x][y]->Sub->Life <= 0)

我收到编译器错误“请求非结构或 union 中的成员‘Life’”

我应该注意到 header 中的 typedef 是这样声明的

typedef struct Point_s* Point;
typedef struct Submarine_s* Submarine;
typedef struct Command_s* Command;
typedef struct BoardPart_s* BoardPart;

最佳答案

在您的示例中,BoardPart_s 结构的 Sub 字段是 Submarine *,而 Submarine潜艇_s *。因此,要访问该 SubLife 字段,您应该编写 (**(BoardP2[x][y]->Sub)).Life.

为了避免这种困惑,您应该始终避免对类型指针进行类型定义。

关于c - 如何访问作为指针确定的结构体的结构体成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44264733/

相关文章:

c - 将文件读入 C 程序

c# - 如何在C#中实例化堆中的结构

c - 我如何在 C 中使用 kbhit?

c - mremap(2) 与 HugeTLB 改变虚拟地址?

有人可以告诉我错误,因为 pthread_join 不起作用

c 编程搜索文件中的字符串

c++ - 这条线想做什么?

c++ - 在 C++ 中填充仅包含一个 int 数组成员的结构?

c - 指向循环结构体的指针数组

c - 关于读者/作者同步