Re: [語法] 關於 typedef 簡化 多維Arrays 的指標...

看板C_and_CPP (C/C++)作者 (三腳貓的把戲)時間15年前 (2009/10/15 02:35), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串3/4 (看更多)
 首先,感謝阿蓉的愛前輩,我覺得我可能有多瞭解 typedef 一點點,  但我還是想再多問一些觀念...  我試著改寫了一下程式: ========================================================== #include <iostream> using std::cin; using std::cout; using std::endl; int main() { int ia[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11}; typedef int (*array_ptr)[4]; // 這兩行是修改的部份 array_ptr ap = ia; // 我把指標移入了 typedef 中 for(int i=0;i<4;i++) cout << (*ap)[i] << " "; // 這裡是 access 第一行四個元素的程式 // 執行結果會是 0 1 2 3 cout << endl; system("pause"); return 0; } ==========================================================  在 array_ptr 宣告的那一句,整個丟進去上面那行然後去掉typedef,  的確就套進去了,但是,如果套到另一個常見的 typedef 問題: typedef int* intP; const intP p2; 又有點兒套不好,他是 int* const p2 的意思... typedef 後頭接的型態 (int *),就是用 intP 宣告會產生的型態,  而使用 typedef 後的自訂型態來宣告,還可以透過 const 或 * 再進一步修飾,  經由多個例子的歸納,我似乎可以感應到 typedef 各種用法的意思,  但是它究竟實際上的運作全貌,卻還是很模糊... #define、macro,跟 typedef 之間決定性的不同,到底該怎麼說清楚呢 /"\a? ※ 引述《QQ29 (我愛阿蓉)》之銘言: : 其實之前一直把typedef看成類似 define這樣字串取代 : 結果只能看懂簡單的 : typedef int INT; : http://ehome.hifly.to/showthread.php?s=&threadid=132 : 看了這網頁的例子 : 以後看到typedef都把它看成 : typedef int int_array[4]; ← : int_array *ip = ia; : ^^^^整個丟進去上面那行 然後去掉typedef : 就變成 int (*ip)[4]; 其實就是妳寫的那樣了 : 這個看法所有奇怪的typedef都可以這樣套進去 : 還滿好理解的.. : ※ 引述《archon (三腳貓的把戲)》之銘言: : : int ia[3][4]; : : int (*ip)[4] = ia; : : ip = &ia[2]; : : 以上的語法我覺得是蠻直覺的,但是... : : typedef int int_array[4]; ← : : int_array *ip = ia; : : 我始終對 typedef 那一行很困惑... : :  為什麼它不是 typedef int[4] int_array; 呢... : :  這個玩意兒,是本來就如此,還是說可以有一個比較令人心安的解釋呢... : :  小的斗膽,有請各位大大解惑... <(_ _)> --  追根究底所得到的東西,是失望的觀眾,以及狼狽的魔術師... De'Ring Practice http://www.wretch.cc/blog/miauwally/21246514 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.24.8.187

10/15 03:57, , 1F
typedef真的不是macro 不要那樣想 會很死
10/15 03:57, 1F

10/15 09:44, , 2F
我想推「感應到 typedef 各種用法的意思」lol
10/15 09:44, 2F
文章代碼(AID): #1ArXdZYB (C_and_CPP)
文章代碼(AID): #1ArXdZYB (C_and_CPP)