前言

结构指针与结构数组,他们一起使用时会更加方便。就像指针和数组。

  1. 结构指针的声明
    struct guy * him

  2. 指向 him = &fellow[0]
    但是有一点需要注意:单纯的结构数组名没有作用
    数组的变量名是数组的首元素地址。结构数组的变量名不是结构数组的首结构地址
    所以但要将首结构的地址赋给指针时,要加上&和[0]

  3. 用指针访问
    him->handle.first//意义:用him指针指向成员的成员
    等价于
    (*him).handle.first//意义:取值为结构struct guy fellow[0]这个结构
    这里必须要用(),因为.比*的优先级高。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* 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",
68112.00
},
{{"Rodney", "Swillbelly"},
"tripe",
"tabloid editor",
432400.00
}
};
struct guy * him; /* here is a pointer to a structure */

printf("address #1: %p #2: %p\n", &fellow[0], &fellow[1]);
him = &fellow[0]; /* tell the pointer where to point */
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++; /* point to the next structure */
printf("him->favfood is %s: him->handle.last is %s\n",
him->favfood, him->handle.last);

return 0;
}