union和内存对齐的小例子

来源:互联网 发布:java制作骰子 编辑:程序博客网 时间:2024/05/17 06:07

union和内存对齐的小例子

下面这两个例子,包含了两个知识点:
1. union共用内存首地址
2. 结构体内存对齐

例子1:

#include <stdio.h>#include <iostream>using namespace std; /*union 共用体,完全共用一个内存首地址,针对union中变量的操作共同生效*/ /*牵一发而动全身,a、b中的任意一个变了,另一个也变了*/typedef union{    int a;    int b;}Demo;union {       char mark; //1     long num; //4    int a; //4     float b; //4    double c; //8}student;/*结构体大小是结构体中各变量所占大小的最小公倍数*//*且这个最小公倍数要大于所有变量所占内存大小的总和*/struct{      char mark; //1 (补3)    long num;  //4    int a;     //4     float b;   //4    double c;  //8} student2 ;int main() {    Demo d;    d.a = 10;    d.b = 12;    printf("size:%d\n", sizeof(d)); // int占4个字节    printf("%d\t%d\n",d.a,d.b); // 12  12 “牵一发而动全身”    // 内存首地址共用    cout<<sizeof(student)<<endl; //8    //(1+3)+4+4+4+8 = 24    cout<<sizeof(student2)<<endl; //24    return 0;}

运行结果如下:

这里写图片描述

例子2:

#include <iostream>using namespace std;struct st1 {    char a ; //1 补充3     int  b ; //4     short c ;//2 补充2 };struct st2 {    short c ; //2     char  a ; //1 补充1     int   b ; //4  };int main() {    cout<<"sizeof(st1) is "<<sizeof(st1)<<endl; // 12    cout<<"sizeof(st2) is "<<sizeof(st2)<<endl; // 8    return 0 ;}

这里写图片描述

参考:

内存对其: http://blog.chinaunix.net/uid-26548237-id-3874378.html

这里写图片描述

原创粉丝点击