指向結(jié)構(gòu)的指針
為什么使用指向結(jié)構(gòu)的指針?
1 就像指向數(shù)組的指針比數(shù)組本身更容易操作一樣,指向結(jié)構(gòu)的指針通常都比結(jié)構(gòu)本身更容易操作.
2 在一些早期的 C 實(shí)現(xiàn)中,結(jié)構(gòu)不能作為參數(shù)被傳遞給函數(shù),但指向結(jié)構(gòu)的指針可以.
3
許多奇妙的數(shù)據(jù)表示都使用了包含指向其他結(jié)構(gòu)的指針的結(jié)構(gòu).
下面是個(gè)例子:
/* 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;??? /* 聲明指向結(jié)構(gòu)的指針,這個(gè)聲明不是建立一個(gè)新的結(jié)構(gòu),而是意味
著指針him現(xiàn)在可以指向任何現(xiàn)有的guy類(lèi)型的結(jié)構(gòu)*/
??
??? printf("address #1: %p #2: %p\n", &fellow[0], &fellow[1]);
??? him = &fellow[0];??? /* 告訴該指針?biāo)赶虻牡刂? */
??? 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++;?????????????? /*指向下一個(gè)結(jié)構(gòu)*/
??? printf("him->favfood is %s:? him->handle.last is %s\n",
???????? him->favfood, him->handle.last);
???
??? return 0;
}
輸出結(jié)果:
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
.這是因?yàn)槊總€(gè)
guy
結(jié)構(gòu)占用了
84
字節(jié)的內(nèi)存區(qū)域.
使用指針訪問(wèn)成員的方法:
1 him->income 但是不能 him.income ,因?yàn)?/span> him 不是一個(gè)結(jié)構(gòu)名.
2
如果
him=&fellow[0],
那么
*him=fellow[0]
.因?yàn)?/span>
&
與
*
是一對(duì)互逆的運(yùn)算符.因此,可以做以下替換:
fellow[0].income= =(*him).income
注意這里必須要有圓括號(hào),因?yàn)?/span>
.
運(yùn)算符比
*
的優(yōu)先級(jí)高.
?
?