Kri*_*oks 1 c struct structure
我有一个指向结构的指针,我想通过反复试验获取所有成员.我试图通过将指针递增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
}
}
Run Code Online (Sandbox Code Playgroud)
PS我知道我不应该这样做,但这仅用于测试目的.
因为InHeadP是a mach_msg_header_t*,向它添加一个整数实际上会添加整数倍sizeof(mach_msg_header_t),就好像你索引一个mach_msg_header_ts 数组(实际上是数组索引的工作原理).你需要转换InHeadP到int* 之前在其上进行运算,即使如此,与结构有六个字段,i只应上升到6,而不是24.