[問題] 指標運算的型別轉換?
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
Linux
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
No
問題(Question):
指標運算的型別轉換問題
餵入的資料(Input):
int *a_ptr
預期的正確結果(Expected Output):
return (struct s*)((char*)a_ptr - (int)&((struct s*)0)->a);
錯誤結果(Wrong Output):
無
程式碼(Code):(請善用置底文網頁, 記得排版)
某 struct s, 內含 member a,
struct s
{
...
int a;
…
};
傳入 member a 的指標, 求傳回 struct s 的指標..
struct s* get_s_ptr(int *a_ptr)
{
return (struct s*)((char*)a_ptr - (int)&((struct s*)0)->a);
}
補充說明(Supplement):
我想請問 a_ptr 為何要先轉換成 (char*) 才去減右邊?
其中右邊為了被減還特地轉換成 (int)..
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 96.55.113.197
→
03/29 10:34, , 1F
03/29 10:34, 1F
→
03/29 10:35, , 2F
03/29 10:35, 2F
→
03/29 10:36, , 3F
03/29 10:36, 3F
感謝, 我試著解釋看看:
左邊是位址, 要轉換成 char *, 才能把加減時的單位轉換成 1.
右邊本來是位址, 強制轉換成 int 後, 才能合法成為被減的數字.
推
03/29 12:32, , 4F
03/29 12:32, 4F
→
03/29 12:37, , 5F
03/29 12:37, 5F
※ 編輯: supisces 來自: 96.55.113.197 (03/30 07:17)