Structure - Access Structure element without . and ->

后端 未结 2 1644
北海茫月
北海茫月 2021-01-27 16:06

I am required to access some elements from nested structure without using . and ->

I need to print out the values for keyValue

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-27 16:24

    Probably they want you to use something like this:

    union {
        mouse_S    mouse;
        keyboard_S keyboard;
        laptop_S   laptop;
    } * oh; // oh = offset helper
    size_t offset_of_mouse_leftButton = (char*)&oh->mouse->leftButton - (char*)&oh->mouse; // this should be 0
    size_t offset_of_mouse_rightButton = (char*)&oh->mouse->rightButton - (char*)&oh->mouse; // but this one can be anything
    size_t offset_of_mouse_middleButton = (char*)&oh->mouse->middleButton - (char*)&oh->mouse; // this too
    // ...
    size_t offset_of_keyboard_alternateKeyValue = (char*)&oh->keyboard->alternateKeyValue - (char*)&oh->keyboard;
    // ...
    

    and then with a void * to keyboard_S:

    int get_keyValue(void * _keyboard) {
        // usual way:
        // keyboard_S * keyboard = _keyboard;
        // return keyboard->keyValue;
        // requested way:
        return *(CHAR*)((char*)_keyboard + offset_of_keyboard_keyValue);
    }
    

    The type CHAR should be written in lowercase and is the type of the element keyValue. The other char must be char for every type, whatever it is. Same for the chars above in the offset_of_ variable definitions.

    So, I guess, the rest is your homework.

提交回复
热议问题