我的问题是如何访问结构details_1和details_2的元素?

问题描述 投票:0回答:1
    ```
    typedef struct{
    unsigned char student;
    unsigned int roll_no;
    }details_1;

    typedef struct{
    unsigned long pin_code;
    unsigned char birthdate;
   }details_2;

   typedef union{
   details_1  COUNT8;
   details_2  COUNT16;
   }details_union;

   ```

我如何访问结构details_1和details_2的元素?

请帮助我。预先感谢。

c unions
1个回答
0
投票

使用点运算符访问结构成员。对于指针变量,请使用->运算符。

details_1 d1 = {'c', 1};
details_2 d2 = {999999,'b'};
details_union du = {d1};
printf ("Access student directly: %c\n",d1.student);
printf ("Access student through union: %c\n",du.COUNT8.student);
printf ("Access pin_code through union: %lu\n\n",du.COUNT16.pin_code);  // not this value

du.COUNT16=d2;
printf ("Access pin_code directly: %lu\n",d2.pin_code);
printf ("Access pin_code through union: %lu\n",du.COUNT16.pin_code);
printf ("Access student through union: %c\n",du.COUNT8.student); // not this value
© www.soinside.com 2019 - 2024. All rights reserved.