当结构体遇到数组,简直了!!!

#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)个字节的位置,然后再字节对齐。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值