Re: [語法] pointer to array請教
推
08/19 05:51,
08/19 05:51
→
08/19 05:51,
08/19 05:51
arr is a pointer to a pointer to an int
→
08/19 05:52,
08/19 05:52
arr is an array of "a pointer to an int" type
→
08/19 05:52,
08/19 05:52
arr is a pointer to an int[COL](an int array type)
→
08/19 05:52,
08/19 05:52
推
,
其實有一定的規則可循,The C programming language(K&R)有提到這方法
從宣告名稱開始分析(即此處的arr)
int * * (arr) -> arr is a/an
int * (*arr) -> arr is a pointer
int (**arr) -> arr is a pointer to a pointer
(int **arr) -> arr is a pointer to a pointer to an int
int *(arr)[COL] -> arr is a/an
int *(arr[COL]) -> arr is an array(此處要注意[]的prior比*高)
int (*arr[COL]) -> arr is an array of pointer
(int *arr[COL]) -> arr is an array of pointer to an int
int (arr)[][COL] -> arr is a/an
int (arr[])[COL] -> arr is a pointer(在C裡arr[]等同於*arr,K&D裡建議用後者
以明確指出是以pointer傳入)
int (arr[][COL]) -> arr is a pointer to an array
(int arr[][COL]) -> arr is a pointer to an array of int
在這裡還有一點要指出 arr[ROW][COL]和arr[][COL]不是同一種型態
前者是array type,可decay成int (*) [COL]型態,且無法改變其值(ex:++arr//error)
而arr[][COL]等同於int (*)[COL],可改變其值
array和pointer是不同type!
--
其他還有像是加上const修飾
一般我們會用const Type這種方式宣告一個constant obj
但是如果有很複雜型態的情況下 我比較prefer將const修飾加在後面
例如大家都知道:
const int *const -> a const pointer to a const int
若是改成
int const *const ->同上
就可以很清楚看出來 const就是修飾於他前面的型態
如此一來
int const *const *const -> a const pointer to a const pointer to a const int
int **const -> a const pointer to a pointer to a int
int **const* -> a pointer to a const pointer to a pointer to a int
就可以很清楚的看出來了。
配合上typedef
typedef int * PI;
const PI -> const int*? int *const?
若是這樣看
PI const -> int *const
typedef int const* PCI;
PCI const -> int const *const
typedef int const *const CPCI;
CPCI const -> int const *const
這樣也好判斷多了
最後有關constant pointer型態轉換的問題
可以參考神人tinlans大的文章 #1B_2w2Uj
如果沒看到這個 還真一輩子不會發現有這問題...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.36.168.54
→
08/19 08:52, , 1F
08/19 08:52, 1F
→
08/19 08:55, , 2F
08/19 08:55, 2F
我在最開始加了個註解 "a pointer to an int"是一種type
而arr是此type的array...
→
08/19 09:00, , 3F
08/19 09:00, 3F
→
08/19 09:01, , 4F
08/19 09:01, 4F
→
08/19 09:05, , 5F
08/19 09:05, 5F
其實我比較喜歡用"從identifier開始,再判斷結合的prior"來說明...像[]就是往右結合
推
08/19 09:30, , 6F
08/19 09:30, 6F
→
08/19 09:46, , 7F
08/19 09:46, 7F
※ 編輯: hilorrk 來自: 114.36.168.54 (08/19 10:58)
推
08/19 12:33, , 8F
08/19 12:33, 8F
→
08/19 12:33, , 9F
08/19 12:33, 9F
推
08/19 12:50, , 10F
08/19 12:50, 10F
→
08/19 12:51, , 11F
08/19 12:51, 11F
→
08/19 18:23, , 12F
08/19 18:23, 12F
推
08/19 19:32, , 13F
08/19 19:32, 13F
→
08/19 19:33, , 14F
08/19 19:33, 14F
→
08/19 19:33, , 15F
08/19 19:33, 15F
→
08/19 19:33, , 16F
08/19 19:33, 16F
→
08/19 19:34, , 17F
08/19 19:34, 17F
→
08/20 11:31, , 18F
08/20 11:31, 18F
討論串 (同標題文章)
完整討論串 (本文為第 3 之 4 篇):