c - 结构 - 访问不带 .和 ->

标签 c pointers struct

我需要在不使用 .->

的情况下访问嵌套结构中的某些元素

我需要在不使用 .-> 的情况下从测试笔记本电脑定义中打印出 keyValuealternateKeyValue 的值 运算符直接引用 qwerty 结构或其成员。

这是结构。

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 test=
{

    .simpleMouse =
    {
        .leftButton = false,
        .rightButton = false,
        .middleButton = false,
        .mouseOn = false,
        .direction = MOUSE_NONE,
    },
    .qwerty =
    {
        .keyValue = '5',
        .alternateKeyValue = '%'
    },
};

int main()
{

    char c = tesla.qwerty.keyValue;
    char d = tesla.qwerty.alternateKeyValue;
    printf("KeyValue = %c\n", c);
    printf("alternateKeyValue = %c\n", d);
}

这可行,但是有没有一种方法可以在不使用“.”的情况下访问 KeyValuealternateKeyValue

最佳答案

可能他们希望你使用这样的东西:

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;
// ...

然后用 void *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);
}

类型CHAR 应该写成小写,是元素keyValue 的类型。另一个 char 对于每种类型都必须是 char,无论它是什么。与上述 offset_of_ 变量定义中的 char 相同。

所以,我想,剩下的就是你的功课了。

关于c - 结构 - 访问不带 .和 ->,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40353439/

相关文章:

C:如何将字符添加到字符,并在达到最大字符时循环回 'a' ?

编译错误 'undeclared identifier'C

swift - 将结构传递给函数并在函数内创建该结构的实例

c# - 我什么时候应该明确指定一个 StructLayout?

c++ - TCHAR[] 转换为字符串

c++ - 如何在 C/C++ 中运行阿克曼函数而不出错?

c++ - C 或 C++ 中用于数字的二次方的一元运算符

c - 递增计数器时未使用表达式结果

c++ - 内存泄漏,指向文字的指针

C-错误 : storage size of ‘a’ isn’t known