#include <stdio.h>
#include <malloc.h>
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
typedef struct _tag_Test1
{
u32 a;
u8 b;
u8 c;
u16 d;
} Test1;
typedef struct _tag_Test2
{
u16 a;
u8 b;
u8 c;
u32 d;
} Test2;
typedef struct _tag_Test3
{
u8 a;
u8 b;
u8 c;
u8 d;
} Test3;
int main(int argc, char *argv[])
{
int array_length = 20;
char *array = (char *)malloc(array_length * sizeof(char));
int index = 0;
Test1 *t1 = NULL;
Test2 *t2 = NULL;
Test3 *t3 = NULL;
for(index = 0; index < array_length; index++) {
array[index] = index + 1;
}
for(index = 0; index < array_length; index++) {
printf("%d ",array[index]);
}
printf("\n");
t1 = (Test1 *)&array[0];
//或者 t1 = (void *)array;
printf("t1->a = %d\n",t1->a);
printf("t1->b = %d\n",t1->b);
printf("t1->c = %d\n",t1->c);
printf("t1->d = %d\n",t1->d);
t2 = (Test2 *)(t1 + 1);
//或 t2 = (void *)(t1 + 1);
printf("t2->a = %d\n",t2->a);
printf("t2->a = %d\n",t2->b);
printf("t2->b = %d\n",t2->c);
printf("t2->c = %d\n",t2->d);
t3 = (void *)(t2 + 1);
printf("t3->d = %d\n",t3->a);
printf("t3->b = %d\n",t3->b);
printf("t3->c = %d\n",t3->c);
printf("t3->d = %d\n",t3->d);
free(array);
return 0;
}
[centos7@localhost Test1]$ ./struct_pointer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
t1->a = 67305985
t1->b = 5
t1->c = 6
t1->d = 2055
t2->a = 2569
t2->a = 11
t2->b = 12
t2->c = 269422093
t3->d = 17
t3->b = 18
t3->c = 19
t3->d = 20
分析1:
t1 = (Test1 )&array[0]; 或者 t1 = (void )array;
t1->a = 67305985
等价于 t1->a = 0x04030201
具有自动字节对齐功能;
分析2:
t2 = (Test2 )(t1 + 1); 或 t2 = (void )(t1 + 1);
t1 + 1表示 t1偏移sizeof(Test1)个字节;
因此t2指向数组array偏移sizeof(Test1)个字节的位置,然后再字节对齐。