zoukankan      html  css  js  c++  java
  • 联合体名字的含意

    #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 便可以取出变量的值

  • 相关阅读:
    【Codeforces542E】Playing on Graph [Bfs][Dfs]
    【Codeforces441E】Valera and Number [DP]
    单链表快速排序
    一个简易内存池(C++)
    最长回文子串---Manacher算法
    hihocoder 1015题
    简单的字典树(前缀树)
    C++获取基类指针所指子类对象的类名
    Muduo阅读笔记---net(三)
    C++线程安全的单例模式
  • 原文地址:https://www.cnblogs.com/taek/p/3935737.html
Copyright © 2011-2022 走看看