2013-02-09 78 views
-1

我的代碼是什麼樣的一些這樣的:如何訪問一個指向另一個結構中聲明的結構?

struct a{ 
      .... 
      .... 
      }; 
    struct a c[MAXNODES]; 

    struct b{ 
      int k; 
      struct a *p; 
      }; 
    struct b d[MAXNODES]; 

所以,如果我需要訪問指針struct astruct b我應該使用間接運算符或沒有。

some_variable=*(d.[i-1].p); 
+0

這是不明確。爲什麼不能你'D [IDX] .p'? – 2013-02-09 21:24:37

+0

@OliCharlesworth這是一個錯字 – 10111 2013-02-09 21:31:45

回答

1

所以,你有2層的結構,其中一個持有指向其他的一個實例:

typedef struct a { 
    int i; 
} A; 

typedef struct b { 
    A *pA; 
} B; 

然後某處,你有你的結構,其中struct a實例駐留的數組:

A arr[10]; 

B b; 
b.pA = &arr[0]; // makes b.pA to point to the address of first element of arr 
b.pA->i = 2; // equivalent to (*b.pA).i = 2; 

A a = *b.pA; // creates a copy of an element that b.pA points to 
A* pA = b.pA; // stores the reference (copies the pointer) 
相關問題