簡體   English   中英

如何訪問被設置為指針的結構的結構成員?

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

我試圖在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

但是當我試圖像這樣強調它的成員生活時

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

我收到一個編譯器錯誤“在結構或聯合中請求成員'Life'”

我應該注意,標頭中的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 * ,而SubmarineSubmarine_s * 因此,要訪問該SubLife字段,您應該編寫(**(BoardP2[x][y]->Sub)).Life

為了避免這種混亂,您應該始終避免對類型指針的類型定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM