c - Access structure members without using '.' or '->' operator -
this question has answer here:
how access keyvalue , alternatekeyvalue dell laptop definition without using '.' or '->' operators directly reference qwerty struct or members.
i tried looking solution didn't find any. please me find way access it?
typedef enum { mouse_none, mouse_up, mouse_down, mouse_left, mouse_right, } mouse_direction_e; typedef struct { bool leftbutton; bool rightbutton; bool middlebutton; bool mouseon; mouse_direction_e direction; } mouse_s; typedef struct { char keyvalue; char alternatekeyvalue; } keyboard_s; typedef struct { mouse_s simplemouse; keyboard_s qwerty; } laptop_s; laptop_s dell = { .simplemouse = { .leftbutton = false, .rightbutton = false, .middlebutton = false, .mouseon = false, .direction = mouse_none, }, .qwerty = { .keyvalue = '5', .alternatekeyvalue = '%' }, };
this sounds homework question....
howzabout this:
int index = 0; bool leftmousebutton = *( (bool *) &( ( (char*) &dell )[0]) ); /* \ 1 / * \ 2 / * \3/ * \___________ 4 _________/ * \_ 5 _/ * \_________________ 6 _________________/ */ bool rightmousebutton = *( (bool *) &( ( (char*) &dell )[ sizeof(bool) - 1 ]) ); /* etc. enjoy math! */
in words:
for struct element located x
bytes deep dell
- get address of
dell
- cast address ptr array of bytes (chars) -- or if of struct content same size
int
, cast addressint*
(remember adjust subsequent math accordingly!) - determine offset of desired element start of struct
dell
. - get address desired element.
- cast address ptr of same type element we're presently working with.
- get data @ address of element we're presently working with. in other words: value of element.
tell me how did on assignment!
Comments
Post a Comment