PakkyaHadpad PakkyaHadpad - 26 days ago 5
C Question

Access structure members without using '.' or '->' operator

How do I access keyValue and alternateKeyValue from the dell laptop definition without using the '.' or '->' operators to directly reference the qwerty struct or its members.

I tried looking for the solution but didn't find any. Could you please help me find a way to 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 = '%'
},
};

Answer

This sounds like a 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 the math! */

in words:

For any struct element located x bytes deep into dell

  1. get the address of dell
  2. Cast the address to a ptr to an array of bytes (chars) -- or if all of the struct content is the same size as int, then cast the address to int* (Remember to adjust subsequent math accordingly!)
  3. Determine the offset of the desired element from the start of the struct dell.
  4. Get the address for the desired element.
  5. Cast that address to a ptr of the same type as the element we're presently working with.
  6. Get the data at the address of the element we're presently working with. In other words: get the value of the element.

Tell me how I did on the assignment!