Re: [問題] 指標

作者: OPIV (Monitor)   2015-06-17 15:14:47
※ 引述《GooLoo (平凡)》之銘言:
: 開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
: 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
: 問題(Question):
: 請問一下
: *與&最大不同是
: *a : a的內容 &a : a的位址
: 最近在看一份範例程式,它用了很多指標,
: 我想瞭解程式內容,並用自己看得懂的方式重寫
: 其中,
: uint16_t moved_perm(uint8_t *buf)
: {
: uint16_t plen;
: plen=fill_a(buf,0,PSTR("123"));
: return(plen);
: }
: *buf =>動作不是很懂 ,平常寫都沒星號,
: 有人可以舉例說明, 差異跟應該會得到的結果嗎?
: 我google過, 多半看不懂, 或是只教*與&的不同,
: 針對函式中的參數有星號沒有特別的說明
: 可否請高手指點, 這種參數內有指標的意義
: 另外buf應該是一個陣列?那可以帶到函式參數內?
: 謝謝
: 餵入的資料(Input):
: 預期的正確結果(Expected Output):
: 錯誤結果(Wrong Output):
: 程式碼(Code):(請善用置底文網頁, 記得排版)
: 補充說明(Supplement):
你的問題去書上找"變數"應該會有答案
在這裡分享我當初是怎麼搞懂指標的(僅限語法上)希望對你有幫助
首先 一個變數包含這些東西
1. 變數名稱
2. 變數型態
3. 變數在記憶體中的位址
4. 變數的值
1. 變數名稱只在程式碼裡有意義,簡單來說就是讓你可以用一個名子來操作記憶體
2. 告訴程式這個變數需要多少記憶體,要怎麼轉成人看得懂的格式 etc......
3. 變數要放東西進去一定要有個空間,記憶體位址就是系統分配給變數的空間的位址
4. 變數的內容就看你要放什麼東西進去了,變數的值的意義只有你自己懂,純看你如何
用它
那首先看怎麼宣告變數(可以去參考 right-left rule)
宣告型態為 (int) 的變數
int a; // (int) a,a 的型態是(int)
int b; // (int) b,b 的型態是(int)
int c; // (int) c ,c 的型態是(int)
宣告型態為 (int *) 的變數
int *a; // (int *) a,變數 a 的型態是 (int *),(int) *a,變數 *a 的型態是(i
nt)
int *b; // (int *) b 打字好累
int *c; // (int *) c 打字好累
宣告型態為 (struct Node) 的變數
struct Node a; // @#~!*&#^&@
struct Node b;ꀠꀠ// @#~!*&#^&@
struct Node c;ꀠꀠ// @#~!*&#^&@
看出來了沒?
來舉個例子:
struct Node *node = NULL;
node 的型態是 (struct Node *) // (struct Node *)node = NULL
*node 的型態是 (struct Node) // (struct Node) *node = NULL
所以 node 裡裝的是 NULL,*node 的值就是 NULL 這個位址裡的型態為(struct Node)的
變數的值(當然,這個位址可能是 alloc 來的,不屬於別的變數)
第一種常見的指標用法:
struct Node node = {NULL, NULL, 0}; // 先宣告一個一般的變數
struct Node *node_ptr = &node; // 再宣告一個指標,把一般變數的位址存進指標

來看看變數們的詳細內容:
node:
node 的型態:struct Node
node 的記憶體位址:&node
node 的值:{NULL, NULL, 0}
node_ptr:
node_ptr 的型態:struct Node *
node_ptr 的記憶體位址:&node_ptr
node_ptr 的值:&node
第二種常見用法:
struct Node *node_ptr = (struct Node)malloc(sizeof(struct Node)); // 向系統
取得一塊大小為sizeof(struct Node)的記憶體,再把位址塞到 node_ptr 裡面
再看一次變數的資料:
*node_ptr:
*node_ptr 的型態:struct Node
*node_ptr 的記憶體位址:沒有這種東東
*node_ptr 的值:系統分記憶體給你的時候裡面裝了什麼,你拿到裡面就是什麼(只有全
域變數會自動初始化)
node_ptr:
node_ptr 的型態:struct Node *
node_ptr 的記憶體位址:&node_ptr
node_ptr 的值:malloc 傳回來的位址
簡單的變數型態就把前面括起來,型態就出來了
(int *) a, b, c;
(const char *const) a;
(const char)* const a;
如果是函式指標,就用 right-left rule 吧!

Links booklink

Contact Us: admin [ a t ] ucptt.com