首先讓我們定義結構體:
struct stu { char name[20]; long number; float score[4]; } ;
再定義指向結構體類型變量的指針變量:
struct stu *p1, *p2 ;
定義指針變量p 1、p 2,分別指向結構體類型變量。引用形式為:指針變量→成員;
[例7-2] 對指向結構體類型變量的正確使用。輸入一個結構體類型變量的成員,並輸出。
#include <stdlib.h> /*使用m a l l o c ( ) 需要* / struct data / *定義結構體* / { int day,month,year; } ; struct stu /*定義結構體* / { char name[20]; long num; struct data birthday; /嵌*套的結構體類型成員*/ } ; main() /*定義m a i n ( ) 函數* / { struct stu *student; 定/*義結構體類型指針*/ student=malloc(sizeof(struct stu)); 為/指* 針變量分配安全的地址*/ printf("Input name,number,year,month,day:/n"); scanf("%s",student->name); 輸/*入學生姓名、學號、出生年月日*/ scanf("%ld",&student->num); scanf("%d%d%d",&student->birthday.year,&student->birthday.month, &student->birthday.day); printf("/nOutputname,number,year,month,day/n"); /*打印輸出各成員項的值*/ printf("%20s%10ld%10d//%d//%d/n",student->name,student->num, student->birthday.year,student->birthday.month, student->birthday.day); } 程序中使用結構體類型指針引用結構體變量的成員,需要通過C提供的函數malloc()來為 指針分配安全的地址。函數sizeof()返回值是計算給定數據類型所占內存的字節數。指針所指 各成員形式為: student->name student->num student->birthday.year student->birthday.month student->birthday.day
指向結構體類型數組的指針的使用
定義一個結構體類型數組,其數組名是數組的首地址,這一點前面的課程介紹得很清楚。
定義結構體類型的指針,既可以指向數組的元素,也可以指向數組,在使用時要加以區分。
[例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等。 [例7-4]指向結構體數組的指針變量的使用。 structdata/*定義結構體類型*/ { intday,month,year; }; structstu/*定義結構體類型*/ { char name[20]; long num; struct data birthday; }; main() {inti; structstu*p,student[4]={{"liying",1,1978,5,23},{"wangping",2,1979,3,14}, {"libo",3,1980,5,6},{"xuyan",4,1980,4,21}}; /*定義結構體數組並初始化*/ p=student;/*將數組的首地址賦值給指針p,p指向了一維數組student*/ printf("/n1----Outputname,number,year,month,day/n"); for(i=0;i<4;i++)/*采用指針法輸出數組元素的各成員*/ printf("%20s%10ld%10d//%d//%d/n",(p+i)->name,(p+i)->num, (p+i)->birthday.year,(p+i)->birthday.month, (p+i)->birthday.day); }
轉自:http://www.21shipin.com/html/93323.shtml