把结构体与数组之间的转换

二维数组和一维数组的转换很简单,直接是强制转换即可,例如:

#include
#include
unsigned char aa[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};

int main(){
    int i;

    for(i = 0;i < 16;i++){
        printf("%d ",((unsigned char *)aa)[i]);
    }

}

打印结果:

把结构体与数组之间的转换_第1张图片

如果是定义一个结构体呢:

struct cc
{
    unsigned char data1[6];
    unsigned char data2;
    unsigned char data3;
    unsigned char data4[31];
};

main函数里面定义变量初始化

 

    struct cc dd = {
        .data1 = {1,2,3,4,5,6},
        .data2 = 7,
        .data3 = 8,
        .data4 = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1}
        
    };

    for(i = 0;i < 39;i++){
        printf("%d ",((unsigned char *)&dd)[i]);
    }

打印结果:

把结构体与数组之间的转换_第2张图片

如果是结构体里面套结构体呢?

下面给一个完整可以运行的程序:

#include
#include
unsigned char aa[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
struct cc
{
    unsigned char data1[6];
    unsigned char data2;
    unsigned char data3;
    unsigned char data4[31];
};
struct ee{
    struct cc ff[4];    
};
int main(){
    int i;
    struct cc dd = {
        .data1 = {1,2,3,4,5,6},
        .data2 = 7,
        .data3 = 8,
        .data4 = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1}
        
    };
    struct ee bb = {
        .ff = {
                {    
                    .data1 = {1,2,3,4,5,6},
                    .data2 = 7,
                    .data3 = 8,
                    .data4 = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1}
                },
                {    .data1 = {1,2,3,4,5,6},
                    .data2 = 7,
                    .data3 = 8,
                    .data4 = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1}
                },
                {        
                    .data1 = {1,2,3,4,5,6},
                    .data2 = 7,
                    .data3 = 8,
                    .data4 = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1}
                },
                {        
                    .data1 = {1,2,3,4,5,6},
                    .data2 = 7,
                    .data3 = 8,
                    .data4 = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1}
                }
        }
    };
    
    
    for(i = 0;i < 16;i++){
        printf("%d ",((unsigned char *)aa)[i]);
    }
    printf("\n\n");
    for(i = 0;i < 39;i++){
        printf("%d ",((unsigned char *)&dd)[i]);
    }
    
    printf("\n\n");
    for(i = 0;i < 39*4;i++){
        printf("%d ",((unsigned char *)&bb)[i]);
    }
}


 


打印结果:

把结构体与数组之间的转换_第3张图片

你可能感兴趣的:(编程小记,强制类型装换)