1. 程式人生 > >結構體(Union)記憶體分配

結構體(Union)記憶體分配

#include <stdio.h>
#include <iostream>
using namespace std;

union U1
{
	char s[9]; //偏移為0
	int n;	   //偏移為0
	double d;  //偏移為0
};

union U2
{
	char s[5];
	int n;
	double d;
};

int main(int argc, char *argv[])
{
	U1 u1;
	U2 u2;
	u1.n = 0x010203;

	printf("sizeof(U1) = %d\n", sizeof(U1));
	printf("sizeof(U1) = %d\n", sizeof(U2));
	printf("addr(u1)                    = 0x%x\n", &u1);
	printf("addr(u1.s) %% sizeof(double) = 0x%x %% %d = %d\n", &u1.s, sizeof(double), (unsigned long)(&u1.s) % (sizeof(double)));
	printf("addr(u1.n) %% sizeof(int)    = 0x%x %% %d = %d\n", &u1.n, sizeof(int), (unsigned long)(&u1.n) % (sizeof(int)));
	printf("addr(u1.d) %% sizeof(char)   = 0x%x %% %d = %d\n", &u1.d, sizeof(char), (unsigned long)(&u1.d) % (sizeof(char*)));
	printf("--------------------------------------\n");

	system("pause");
	return 0;
}

點選開啟連結 

佔用記憶體為聯合體中最大的變數長度的整數倍(特別注意陣列)

參考文獻: