联合体名字的含意

#include <stdio.h>
#include <stdlib.h>
int main()
{

    union test
    {
        int a;
        int b;
    }t1;

    t1.b=2;
    printf("t1 value  is %p\n",t1);
    printf("a value is %d\n",t1.a);
    printf("b value is %d\n",t1.b);
    printf("-------------\n");
    printf("t1 address is %p\n" , &t1);
    printf("a address is %p\n" , &t1.a);
    printf("b address is %p\n" , &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 便可以取出变量的值

 

posted @ 2014-08-25 20:00  taek  阅读(577)  评论(0编辑  收藏  举报