# 结构体的对齐有关问题

www.MyException.Cn  网友分享于：2013-03-12  浏览：8次

typedef   struct   {
char   c;
short   s;
int   i;
long   l;
float   f;
double   d;
long   double   ld;
}   Primitives;

cout   < <   sizeof(Primitives)   < <   endl;

long只是一个修饰符，long   double不是一种类型

------解决方案--------------------
short不是2字节么？
------解决方案--------------------

typedef struct {
char c; //1
short s; //2
int i; //4
long l; //4
float f; //4
double d; //8
long double ld; //8
} Primitives;

1+(1)+2+4+4+4+8+8=32

------解决方案--------------------
sizeof(long double) 结果是12
cout < < sizeof(Primitives) < < endl;结果是40

------解决方案--------------------

#include <stdio.h>

typedef struct {
char c;
short s;
int i;
long l;
float f;
double d;
long double ld;
} Primitives;

int main(void)
{
Primitives p;

(void) printf( "sizeof(p.c) = %d\n ", sizeof(p.c));
(void) printf( "sizeof(p.s) = %d\n ", sizeof(p.s));
(void) printf( "sizeof(p.i) = %d\n ", sizeof(p.i));
(void) printf( "sizeof(p.l) = %d\n ", sizeof(p.l));
(void) printf( "sizeof(p.f) = %d\n ", sizeof(p.f));
(void) printf( "sizeof(p.d) = %d\n ", sizeof(p.d));
(void) printf( "sizeof(p.ld) = %d\n ", sizeof(p.ld));

(void) printf( "sizeof(p) = %d\n ", sizeof(p));

(void) printf( "address(p.c) = %08x\n ", &(p.c));
(void) printf( "address(p.s) = %08x\n ", &(p.s));
(void) printf( "address(p.i) = %08x\n ", &(p.i));
(void) printf( "address(p.l) = %08x\n ", &(p.l));
(void) printf( "address(p.f) = %08x\n ", &(p.f));
(void) printf( "address(p.d) = %08x\n ", &(p.d));
(void) printf( "address(p.ld) = %08x\n ", &(p.ld));

return 0;
}

XP+VC6下输出：
sizeof(p.c) = 1
sizeof(p.s) = 2
sizeof(p.i) = 4
sizeof(p.l) = 4
sizeof(p.f) = 4
sizeof(p.d) = 8
sizeof(p.ld) = 8
sizeof(p) = 32