简体   繁体   中英

How to accsses a struct member of a struct that was setted as a pointer?

I am trying to create a submarine game in c so i made a sturct that will connect the "location" of the submarine on the Board to the submarine it self, these are the structs i use;

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
};

now when the assigment was stated like this

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

however when i try to accses its member life like that

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

i get a compiler error "request for member 'Life' in something not a structure or union"

i should note that the typedef that are in the header are stated like this

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

In your example the Sub field of BoardPart_s struct is Submarine * , and Submarine is Submarine_s * . So to access the Life field of that Sub you should write (**(BoardP2[x][y]->Sub)).Life .

To avoid this kind of confusion you should always avoid typedefing to pointers to types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM