指向结构的指针
				
		
		
				为什么使用指向结构的指针?
		
		
				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 阅读(744) 
评论(0)  编辑  收藏  所属分类: 
阅读笔记