我正在尝试用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 *
。因此,要访问该 Sub
的 Life
字段,您应该编写 (**(BoardP2[x][y]->Sub)).Life
.
为了避免这种困惑,您应该始终避免对类型指针进行类型定义。
关于c - 如何访问作为指针确定的结构体的结构体成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44264733/