Pointer -Declaration Example
這邊給一個例子,也順便說明 struct pointer 的使用。
typedef struct
{
int x;
int y;
} point_t;
我們定義了一個 point_t ,一個平面空間的的整數點。
假設現在有 100 個點灑在平面上,一個可行的做法是使用 array
point_t pts[100];
假設我們做了一些事情,賦予 pts 有意義的值,如亂數或是其他事情。
然後我們決定將它放在 points.c 中
(以下的 source 不一定完整,只說明重要的部分)
// points.h
typedef struct
{
int x;
int y;
} point_t;
// points.c
#include "points.h"
point_t pts[100];
void initPts(void)
{
//初始化 pts
}
當我們在main.c (或是其他檔案) 想讀取 pts 一個簡便可行的做法是 extern point_t pts[100];
這個方法的確在第一時間很"方便",但是在模組化時就會發現他帶來的不便
因為所有人都可以任意改變 pts
可以注意到我剛剛提的是"讀取" pts,也就是說邏輯上 pts 並不需要改變,我們只是要使用值而已。
另外一個可行的做法如下
//points.c
const point_t * getPts(void)
{
return pts;
}
而在外部使用時
//main.c or another source
const point_t * pt = getPts();
printf("%d, %d\n", pt[10].x, pt[10].y);
也許我們可以再變形一下
//points.c
const point_t * getPt(int idx)
{
return pts + idx;
}
來取得第 idx 個 point
而在外部使用時
//main.c or another source
const point_t * pt = getPt(10);
printf("%d, %d\n", pt->x, pt->y);