c - void * assignment problem -


i want take fields packet struct using pointer arithmetic.but wrong code below ?
in first condition think if go 4 byte(2 short field) beginning of packet tlow .but not give expected value.additionally second case want data field going 12 byte beginning of packet .what wrong 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; // want tlow      printf("time low :%d\n",*time);      char *msg = (char *)pck + 12 ;// want data      printf("message :%s\n",msg);      return 0; } 

you better using standard method

int *timelow = &(pck->tlow); 

compilers allowed insert padding bytes between member of struct. rules these padding bytes are, @ best, implementation defined ... must consult implementation manual how (or if) , how many bytes inserted in specific case. note number of padding bytes might change compilation compilation different options or compiler compiler (computer computer, ...)

you can try use c macro offsetof, it's not pretty:

size_t offset = offsetof(struct packet, tlow); /* make sure offset multiple of sizeof (int*) */ int *timelow = (int*)pck + offset / sizeof (int*); 

or, little less ugly using cast (char*) and copying code other answers :-)

size_t offset = offsetof(struct packet, tlow); int *timelow = (int*)((char*)pck + offset); 

oh! , there's semi-colon missing in source


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -