我有一個指向結構的指針,我想通過試驗和錯誤獲取其所有成員。我試圖通過將指針遞增1並去除它來運行結構。它應該從結構中返回一個正確的值(每i*sizeof(int)
時間),但它不會。運行結構並打印所有值?
我在做什麼錯?
fn (mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)
{
/*
assume that all struct members are int types
typedef struct
{
mach_msg_bits_t msgh_bits;
mach_msg_size_t msgh_size;
mach_port_t msgh_remote_port;
mach_port_t msgh_local_port;
mach_msg_size_t msgh_reserved;
mach_msg_id_t msgh_id;
} mach_msg_header_t;
size of the struct is 24.
*/
printf("ID: %d \n",InHeadP->msgh_id); //prints 'ID: 1337'
printf("Ptr: %p\n",InHeadP);
for (int i = 0; i <= 24; i++)
{
int deref = *((int*)(InHeadP+i));
printf("InHeadP[%d]=%d\n",i,deref);
//no sign of 1337 anywhere
}
}
P.S.我知道我不應該那樣做,但這只是爲了測試目的。
'INT * deref'?你不是指'int deref'嗎? – nmichaels 2011-05-20 15:41:19
是的。 'int deref = *((int *)(InHeadP + i))'。改變了它。 – 2011-05-20 15:41:45
「它應該從結構中返回一個正確的值(每個I * sizeof(int)時間),但它不會。」 - 呃爲什麼要這樣?這不完全是如何分配內存。 – zellio 2011-05-20 15:42:32