注意:结构体定义后面要加分号;
结构体指针的访问要用->,p->name;
1 指向结构体类型数组的指针的使用
定义一个结构体类型数组,其数组名是数组的首地址,这一点前面的课程介绍得很清楚。
定义结构体类型的指针,既可以指向数组的元素,也可以指向数组,在使用时要加以区分。
[例7-3] 在例7 - 2中定义了结构体类型,根据此类型再定义结构体数组及指向结构体类型的指针。
struct data
{
intday,month,year;
};
struct stu/*定义结构体*/
{
char name[20];
long num;
struct data birthday;/嵌*套的结构体类型成员*/
};
struct stustudent[4],*p;定/*义结构体数组及指向结构体类型的指针*/
作p=student,此时指针p就指向了结构体数组student。
p是指向一维结构体数组的指针,对数组元素的引用可采用三种方法。
1)地址法
student+i和p+i均表示数组第i个元素的地址,数组元素各成员的引用形式为:
(student+i)->name、(student+i)->num和(p+i)->name、(p+i)->num等。student+i和p+i
与&student[i]意义相同。
2)指针法
若p指向数组的某一个元素,则p++就指向其后续元素。
3)指针的数组表示法
若p=student,我们说指针p指向数组student,p[i]表示数组的第i个元素,其效果与
student[i]等同。对数组成员的引用描述为:p[i].name、p[i].num等。
int main()
{
int temp[4] = {1,2,3,4};
int i;
printf("struct\n");
p = student;
for(i=0;i<4;i++)
{
printf("name: %s ,number: %d ,year: %d ,month: %d day: %d \n ",(student+i)->name,(student+i)->num,(student+i)->birthday.year,(student+i)->birthday.month, (student+i)->birthday.day);
}
printf("temp\n");
for(i=0;i<4;i++)
{
printf("*(temp+i)=%d \n",*(temp+i));
}
return 0;
}
输出结果
struct
name: liying ,number: 1 ,year: 23 ,month: 5 day: 1978
name: wangping ,number: 2 ,year: 22 ,month: 3 day: 1979
name: ,number: 0 ,year: 0 ,month: 0 day: 0
name: ,number: 0 ,year: 0 ,month: 0 day: 0
temp
*(temp+i)=1
*(temp+i)=2
*(temp+i)=3
*(temp+i)=4