[問題] 結構指標的問題

看板C_and_CPP作者 (乘風而起)時間13年前 (2011/07/21 20:14), 編輯推噓0(0011)
留言11則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) gcc 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 程式碼: typedef struct notify_buildreq_tag { u32 id; u32 state;} NOTIFY_BUILDREQ; typedef struct notify_process_buildreq_result_tag { u8 result;} NOTIFY_BUILDREQ_RESULT; typedef struct notify_process_tag { u32 state;} NOTIFY_PROCESS; typedef struct notify_process_result_tag { u8 result; u8 done;} NOTIFY_PROCESS_RESULT; typedef struct notify_data_tag { u8 type; union { NOTIFY_BUILDREQ bldReq; NOTIFY_BUILDREQ_RESULT bldReqResult; NOTIFY_PROCESS process; NOTIFY_PROCESS_RESULT processResult; } u; u32 length; // length of the data that follows uint32 addr_length; char addr[16]; } NOTIFY_DATA; main(){ NOTIFY_DATA * recvNotify; recvNotify = (NOTIFY_DATA *) buf; dprintf("[test2.1] ==> %x\n",(recvNotify)); dprintf("[test2] ==> %x\n",(recvNotify + 0x24)); } 餵入的資料(Input): 預期的正確結果(Expected Output): 倆著應該只差offset 0x24 錯誤結果(Wrong Output): offset 510?? [test2.1] ==> 814361e8 [test2] ==> 814366f8 問題 為什麼兩者的差距不適0x24? 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 211.22.66.242

07/21 20:22, , 1F
請用char*...
07/21 20:22, 1F

07/22 03:21, , 2F
猜是1個struct佔36bytes. (recvNotify + 0x24) 移了
07/22 03:21, 2F

07/22 03:22, , 3F
36*36=1296 bytes=0x510 bytes
07/22 03:22, 3F

07/22 04:03, , 4F
寫 0x24 和 36 沒有什麼差別。如果 buf 是一個很大的陣列
07/22 04:03, 4F

07/22 04:05, , 5F
則會移至 36 後的項目。但你用 %x 印指標,型態根本不合,
07/22 04:05, 5F

07/22 04:06, , 6F
最後會印出什麼沒有人知道。剛好差 0x510 沒出事算運氣好.
07/22 04:06, 6F

07/22 04:07, , 7F
(如果 buf 很小,則完全要看實作,標準沒有定義。)
07/22 04:07, 7F

07/22 09:44, , 8F
@Favonia: 我只是解釋為什麼是0x510而非0x24 XD.
07/22 09:44, 8F

07/22 10:03, , 9F
@tropical72 我是在跟原 po 解釋應該會怎樣啦 xD 不是你~
07/22 10:03, 9F

07/22 10:04, , 10F
我覺得他的測試方法本身就有問題了...
07/22 10:04, 10F

07/22 10:08, , 11F
原來如此,誤會一場 XD
07/22 10:08, 11F
文章代碼(AID): #1EA1Wsle (C_and_CPP)