- 论坛徽章:
- 11
|
回复 25# Ager
请问字节填充的规则是怎样的呢?网上说法不一,自己用程序验证如下
编译器类型和系统版本:- root@c-dev:~# gcc --version
- gcc (Debian 4.4.5-8) 4.4.5
- root@c-dev:/c/tlpi# uname -r
- 2.6.32-5-amd64
复制代码 基本数据类型长度:data_type_length.c- #include <stdio.h>
- #define LENGTH(x)\
- printf(""#x" length as byte: %d\n", (sizeof (x)))
- int main (void)
- {
- LENGTH(char);
- LENGTH(int);
- LENGTH(short);
- LENGTH(long);
- LENGTH(float);
- LENGTH(double);
- LENGTH(long double);
- LENGTH(void*);
- return 0;
- }
复制代码 编译运行,- root@c-dev:/c/tlpi# gcc data_type_length.c -o data_type_length
- root@c-dev:/c/tlpi#
- root@c-dev:/c/tlpi# data_type_length
- char length as byte: 1
- int length as byte: 4
- short length as byte: 2
- long length as byte: 8
- float length as byte: 4
- double length as byte: 8
- long double length as byte: 16
- void* length as byte: 8
复制代码 验证代码,align_mem1.c- #include <stdio.h>
- #include <stddef.h>
- int main (void)
- {
- struct MixedData
- {
- char a;
- short b;
- int c;
- long d;
- /*
- short a;
- int b;
- char c;
- long d;
- */
- };
- struct MixedData data0;
- struct MixedData * pt;
- printf ("The addresses:\n");
- printf ("pt = %p,\n&(pt->a) = %p,\n\
- &(pt->b) = %p,\n&(pt->c) = %p,\n&(pt->d) = %p.\n",\
- pt, &(pt->a), &(pt->b), &(pt->c), &(pt->d));
- printf ("\n");
- printf ("offsets: a = %d, b = %d, c = %d and d = %d\n",\
- offsetof (struct MixedData, a), offsetof (struct MixedData, b),\
- offsetof (struct MixedData, c), offsetof (struct MixedData, d));
- printf ("\n");
- printf ("The instance data0\'s length as byte: %d\n", sizeof (data0));
- return 0;
- }
复制代码 编译运行,结构成员以降序排列- root@c-dev:/c/tlpi/iobuf# align_mem1
- The addresses:
- pt = 0x4004a0,
- &(pt->a) = 0x4004a0,
- &(pt->b) = 0x4004a2,
- &(pt->c) = 0x4004a4,
- &(pt->d) = 0x4004a8.
- offsets: a = 0, b = 2, c = 4 and d = 8
- The instance data0's length as byte: 16
复制代码 但是结构成员的顺序会导致结果不同,打乱顺序后,- The addresses:
- pt = 0x4004a0,
- &(pt->a) = 0x4004a0,
- &(pt->b) = 0x4004a4,
- &(pt->c) = 0x4004a8,
- &(pt->d) = 0x4004b0.
- offsets: a = 0, b = 4, c = 8 and d = 16
- The instance data0's length as byte: 24
复制代码 请问结构成员(推广到复合数据结构)的成员数据项间是按照怎样的规则来填充字节的呢? |
|