结构 - 没有的访问结构元素。和 - >

时间:2016-11-01 02:46:00

标签: c pointers struct

我需要从嵌套结构中访问一些元素,而不使用.->

我需要从Test笔记本定义中打印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。'?

2 个答案:

答案 0 :(得分:2)

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

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,无论它是什么。与char变量定义中的offset_of_相同。

所以,我猜,剩下的就是你的作业。

答案 1 :(得分:1)

更直接,更简单的3行代码可以......

//Get the address of the tesla      
  char *addressoftesla  = (laptop_S*)(&tesla);

//structure of tesla = simpleMouse + qwerty + 2 byte paddings

/* Get the value at the starting address of qwerty i.e keyValue*/
  printf("keyValue of tesla keyboard is %c\n",*(addressoftesla+sizeof(mouse_S)));

/* Get the value at the starting address of qwerty i.e alternatekeyValue */
  printf("alternatekeyValue of tesla keyboard is %c\n",*(addressoftesla+sizeof(mouse_S)+1));

  /*
  * More info for further understanding: 
  * A simple check to see all the values in the each field of structure
  * tesla - you can also use sizeof to get the each structure and entire 
  * structure byte sizes and the same can be done using offsetof as in 
  * other solution
  */
  for(int i = 0; i< 12; i++)
  {
      printf("value at tesla[i] is %d \n",*(addressoftesla+i));
  }