结构 - 访问结构元素,不带 .和 -> [英] Structure - Access Structure element without . and ->
问题描述
我需要在不使用 .
和 ->
I am required to access some elements from nested structure without using .
and ->
我需要从测试笔记本电脑定义中打印出 keyValue
和 alternateKeyValue
的值,而不使用 .
或 ->
运算符直接引用 qwerty 结构或其成员.
I need to print out the values for keyValue
and alternateKeyValue
from the Test laptop definition without using the .
or ->
operators to directly reference the qwerty struct or its members.
这是结构.
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
?
This works, but is there a way to access KeyValue
and alternateKeyValue
without using '.'?
推荐答案
可能他们希望你使用这样的东西:
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;
// ...
然后用一个 void *
到 keyboard_S
:
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);
}
类型CHAR
应为小写,是元素keyValue
的类型.对于每种类型,其他 char
必须是 char
,无论它是什么.与上述 offset_of_
变量定义中的 char
相同.
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 char
s above in the offset_of_
variable definitions.
所以,我想,剩下的就是你的家庭作业了.
So, I guess, the rest is your homework.
这篇关于结构 - 访问结构元素,不带 .和 ->的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!