union与struct的区别
2014-12-26 00:25
274 查看
共用体中所有成员公用一块地址空间
结构体中所有成员都有单独的一块地址空间,下面的例子是公用函数指针
下面的例子是公用非函数指针的类型
以下是参考文章
点击打开链接
结构体中所有成员都有单独的一块地址空间,下面的例子是公用函数指针
#include <stdlib.h> #include <stdio.h> typedef void (*FUNC )(void); typedef void (*Func01)(int, int); typedef double (*Func02)(double, double); typedef int (*Func03)(int, int); void Test01(int, int); double Test02(double, double); int Test03(int, int); union UnionTest { FUNC pFunc; Func01 func01; Func02 func02; Func03 func03; }; int main(int argc, char* argv[]) { system("cls"); printf("此程序模仿了MFC中的消息函数分配机制\n"); union UnionTest test; test.pFunc = (FUNC)(static_cast< void (*)(int, int) > (Test01)); printf("%p, %p, %p\n", test.func01, test.func02, test.func03); test.func01(10,10); test.func02(10.111, 20.222); test.func03(10,10); printf("\n"); test.pFunc = (FUNC)(static_cast< double (*)(double, double) > (Test02)); printf("%p, %p, %p\n", test.func01, test.func02, test.func03); test.func01(10,10); test.func02(10.111, 20.222); test.func03(10,10); printf("\n"); test.pFunc = (FUNC)(static_cast< int (*)(int, int) > (Test03)); printf("%p, %p, %p\n", test.func01, test.func02, test.func03); test.func01(10,10); test.func02(10.111, 20.222); test.func03(10,10); printf("\n"); return 0; } void Test01(int x, int y) { printf("Test01\t:\n"); } double Test02(double x, double y) { printf("Test02\t: \n"); return 0; } int Test03(int x, int y) { int sum =x+y; printf("Test03\t:\n"); return 0; }以下是程序的输出结果:
下面的例子是公用非函数指针的类型
#include <stdio.h> union { int i; struct { char first; char second; char third; char fourth; }half; }number; void main() { number.i = 0x87654321; // 87654321 // 214365ffffff87 printf("%x\n", number.i); printf("%x%x%x%x\n", number.half.first, number.half.second, number.half.third, number.half.fourth); number.half.first = 1; number.half.second = 2; number.half.third = 4; number.half.fourth = 8; // 80402010 // 1248 printf("%x\n", number.i); printf("%x%x%x%x\n", number.half.first, number.half.second, number.half.third, number.half.fourth); }
以下是参考文章
点击打开链接
相关文章推荐
- strlen与sizeof区别(转载)以及struct,union的sizeof内存对齐等问题
- 大端小端区别、Union和Struct的内存分配
- C++中的共用体(union)结构解析与结构体(struct)共用体(union) 的区别
- 联合体(union)和结构体(struct)的区别
- 联合体(union)和结构体(struct)的区别
- 大端小端区别、Union和Struct的内存分配、对齐方式
- union 与struct 区别简介
- C语言中union与struct的区别及sizeof的计算方式
- 联合体(union)和结构体(struct)的区别
- struct 与 union 的区别
- 神秘的sizeof(union和struct的区别)
- Union和struct的内存分配区别
- C中的union和struct的区别
- (转载)C中的union和struct的区别,为什么要发明union?
- union 与 struct 区别
- union和struct的区别
- 大小端区别、Union和Struct的内存大小
- Struct 和 Union区别
- union和struct区别
- class struct union 的区别