指向結構的指針
為什么使用指向結構的指針?
1
就像指向數組的指針比數組本身更容易操作一樣,指向結構的指針通常都比結構本身更容易操作.
2
在一些早期的
C
實現中,結構不能作為參數被傳遞給函數,但指向結構的指針可以.
3
許多奇妙的數據表示都使用了包含指向其他結構的指針的結構.
下面是個例子:
/* friends.c -- uses pointer to a structure */
#include <stdio.h>
#define LEN 20
struct names {
??? char first[LEN];
??? char last[LEN];
};
struct guy {
??? struct names handle;
??? char favfood[LEN];
??? char job[LEN];
??? float income;
};
int main(void)
{
??? struct guy fellow[2] = {
??????? {{ "Ewen", "Villard"},
???????? "grilled salmon",
???????? "personality coach",
???????? 58112.00
??????? },
??????? {{"Rodney", "Swillbelly"},
???????? "tripe",
???????? "tabloid editor",
???????? 232400.00
??????? }
??? };
??? struct guy * him;??? /* 聲明指向結構的指針,這個聲明不是建立一個新的結構,而是意味
著指針him現在可以指向任何現有的guy類型的結構*/
??
??? printf("address #1: %p #2: %p\n", &fellow[0], &fellow[1]);
??? him = &fellow[0];??? /* 告訴該指針它要指向的地址? */
??? printf("pointer #1: %p #2: %p\n", him, him + 1);
??? printf("him->income is $%.2f: (*him).income is $%.2f\n",
???????? him->income, (*him).income);
??? him++;?????????????? /*指向下一個結構*/
??? printf("him->favfood is %s:? him->handle.last is %s\n",
???????? him->favfood, him->handle.last);
???
??? return 0;
}
輸出結果:
address #1: 0240FEB0 #2: 0240FF04
pointer #1: 0240FEB0 #2: 0240FF04
him->income is $58112.00: (*him).income is $58112.00
him->favfood is tripe:? him->handle.last is Swillbelly
Press any key to continue...
?
從輸出看出
him
指向
fellow[0],him+1
指向
fellow[1]
.注意
him
加上
1
,地址就加了
84
.這是因為每個
guy
結構占用了
84
字節的內存區域.
使用指針訪問成員的方法:
1
him->income
但是不能
him.income
,因為
him
不是一個結構名.
2
如果
him=&fellow[0],
那么
*him=fellow[0]
.因為
&
與
*
是一對互逆的運算符.因此,可以做以下替換:
fellow[0].income= =(*him).income
注意這里必須要有圓括號,因為
.
運算符比
*
的優先級高.
?
?
posted on 2006-11-09 19:12
matthew 閱讀(718)
評論(0) 編輯 收藏 所屬分類:
閱讀筆記