我需要在不使用 .
和 ->
我需要在不使用 .
或 -> 的情况下从测试笔记本电脑定义中打印出
运算符直接引用 qwerty 结构或其成员。keyValue
和 alternateKeyValue
的值
这是结构。
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);
}
这可行,但是有没有一种方法可以在不使用“.”的情况下访问 KeyValue
和 alternateKeyValue
?
最佳答案
可能他们希望你使用这样的东西:
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/