• 联合体名字的含意


    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
    
        union test
        {
            int a;
            int b;
        }t1;
    
        t1.b=2;
        printf("t1 value  is %p
    ",t1);
        printf("a value is %d
    ",t1.a);
        printf("b value is %d
    ",t1.b);
        printf("-------------
    ");
        printf("t1 address is %p
    " , &t1);
        printf("a address is %p
    " , &t1.a);
        printf("b address is %p
    " , &t1.b);
    
        return 0;
    }
    t1 value  is 0x2
    a value is 2
    b value is 2
    -------------
    t1 address is 0x7ffff9a328e0
    a address is 0x7ffff9a328e0
    b address is 0x7ffff9a328e0

    这里只对联合体的元素b进行赋值,没有对a赋值,但由于联合体的特性:当对某元素赋值后,其他元素将被重写,所以 a的值也为2

    &t1.a 与 &t1.b 相同,也证明了上面的结论 

    变量t1的内存地址 ,与&t1.a , &t1.b一样,所以 t1等于 t1.a,也等于 t1.b

    php中的zval的变量value就是一个union,正好利用union的特性

    typedef struct _zval_struct zval;
    ...
    struct _zval_struct {
        /* Variable information */
        zvalue_value value;     /* value */
        zend_uint refcount__gc;
        zend_uchar type;    /* active type */
        zend_uchar is_ref__gc;
    };
    typedef union _zvalue_value {
        long lval;                  /* long value */
        double dval;                /* double value */
        struct {
            char *val;
            int len;
        } str;
        HashTable *ht;              /* hash table value */
        zend_object_value obj;
    } zvalue_value;

    通过 zval.value 便可以取出变量的值

  • 相关阅读:
    UOJ #276. 【清华集训2016】汽水
    Luogu P4585 [FJOI2015]火星商店问题
    Luogu P5416 [CTSC2016]时空旅行
    NOIP 2011 提高组初赛错题简析
    Luogu P4068 [SDOI2016]数字配对
    UOJ Easy Round #5
    Codechef September Challenge 2019 Division 2
    Project Euler Problem 675
    AtCoder Grand Contest 037
    拿2k的前端开发都会做些什么?
  • 原文地址:https://www.cnblogs.com/taek/p/3935737.html
Copyright © 2020-2023  润新知