在C語言中幾乎可以建立指向任何型別的指標,包括使用者自定義的型別。當然也可以指向結構體,先看一個小案例:
#include <stdio.h> #include <string.h> typedef struct PERSON { int age; int height; char name[15]; } Person; int main (){ Person p = {28, 178, "phper"}; //別名 Person *p_s = &p; //定義結構體指標 printf("%d\t%d\t%s",p_s->age, p_s->height, p_s->name); //等價於 (*p_s).age (*p_s)表示p_s指向的結構體變數 return 0; }
再看一個案例:
#include <stdio.h> #include <string.h> #include <malloc.h> typedef struct PERSON { int age; int height; char name[15]; } Person; int main (){ Person *p_s = (Person *)malloc(sizeof(Person)); //計算結構體Person大小,並分配相應的記憶體空間,也可以傳參(struct PERSON),再強制轉化指標格式 memset(p_s, 0, sizeof(Person)); //分配好空間內容是隨機的,用函式初始化全部清空為0 //指標指向的是p_s的首地址 printf("請輸入年齡:"); scanf("%d", &p_s->age); printf("請輸入身高:"); scanf("%d", &p_s->height); printf("請輸入名字:"); scanf("%s", p_s->name); printf("%d\t%d\t%s",p_s->age, p_s->height, p_s->name); //等價於 (*p_s).age (*p_s)表示p_s指向的結構體變數 return 0; }
指向陣列結構體的指標案例:
# include <stdio.h> # include <stdlib.h> # include <string.h> //建立一個結構體 struct Programmer { int salary; int experience; char type[15]; }programmer[3]= { {18000, 3, "PHP"}, {15000, 1, "GO"}, {19000, 3, "JAVA"}, }; int main () { struct Programmer *pProgrammer; int index; pProgrammer = programmer; for(index=0; index<3; index++,pProgrammer++) //index++後面還有一句控制著指標的移動,迴圈完一次,指標將指向下一個地址中的成員 { printf("編號%d \n",index+1); printf("薪資:%d\n", pProgrammer->salary); printf("經驗-年:%d\n", pProgrammer->experience); printf("崗位:%s\n", pProgrammer->type); } printf("pProgrammer:%d\n&student[2]:%d\n",pProgrammer,&programmer[3]); return 0; }