c - Why accessing fields of struct through a typedef-ed pointer does not work? -


i have these declarations:

typedef struct egobject {     int  magicnumber; } egobject; typedef struct egobject* ego;  ego e; //printf("%d",e->magicnumber); 

i want magicnumber out of e, e->magicnumber doesn't work. what's right way of doing this?

when declare struct, allocate memory struct:

egobject e; 

when declare pointer struct, typedef-ed or not, allocate space pointer, not struct. in order access field of struct need allocate struct first. particular way in not matter - allocate statically, dynamically, or in automated storage, must allocate memory it:

ego e = malloc(sizeof(*e)); 

that enough access field writing. reading field requires initialization, because malloc-ed block contains uninitialized bytes in area allocated magicnumber:

e->magicnumber = 123; 

now can print magicnumber way code did:

printf("%d",e->magicnumber); 

note: if choose dynamic allocation malloc, need free object once done using it:

free(e); // avoid memory leaks 

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -