I want to take some fields from packet struct using pointer arithmetic.But what is wrong with the code below ?
In first condition i think if i go 4 byte(2 short field) from beginning of packet i get tLow .But it does not give expected value.Additionally second case i want to get data field by going 12 byte from beginning of packet .What is wrong with my idea ?
struct packet{
short len;
short field;
int tLow;
int tHigh;
void *data;
}
int main()
{
struct packet pack;
struct packet *pck;
pack.len=3;
pack.field=34;
pack.tLow=712;
pack.tHigh = 12903;
pack.data = "message";
pck = &pack;
int *timeLow = (int * )pck + 4; // i want to get tLow
printf("Time Low :%d\n",*time);
char *msg = (char *)pck + 12 ;// want data
printf("Message :%s\n",msg);
return 0;
}
You definitely would be better using standard method
Compilers are allowed to insert padding bytes between any member of a struct. The rules for these padding bytes are, at best, implementation defined … so you must consult your implementation manual to be certain how (or if) and how many bytes are inserted in your specific case. Also note the number of padding bytes might change from compilation to compilation with different options or from compiler to compiler (computer to computer, …)
You can try to use the
Cmacrooffsetof, but it’s not pretty:or, a little less ugly using a cast to
(char*)and copying the code from other answers 🙂Oh! and there’s a semi-colon missing in your source