pointers - In C: How to point to different members with offset at run time? -
i want use single pointer pt
, offset size_t offp
update value of either mynfo.valuea
or mynfo.valueb
depends on run time conditions.
i can set pt
&mynfo
, not know proper type of pt
, how should calculate offp
.
edited:
i forget mention structures used allocated @ runtime.
i using khash, need distinguish whether key exists. if use
pt = &pnfo->valuea;
, have write similar codes twice. want determine member first , turn hash.
typedef struct { uint16_t valuea; uint16_t valueb; const char * filename; } __attribute__ ((__packed__)) info_t; info_t mynfo, *pnfo; pnfo = calloc(1,sizeof(info_t)); size_t offp = &(mynfo.valueb) - &(mynfo.valuea); if (ret==1) { pt = pnfo; } else { pt = pnfo + offp; } *pt = 100;
use offsetof()
size_t offp; if (some condition) { offp = offsetof(info_t, valuea); } else { offp = offsetof(info_t, valueb); } *(uint16_t*)((char*)pnfo + offp) = 100;
you need pointer casting because offsetof()
returns offset in bytes. first have cast struct pointer char*
add bytes it, cast pointer element type assign it.
Comments
Post a Comment