10 - struct(可变长数组) 和 union 分析

1、 struct的小秘密

这里写图片描述
空结构体占用的内存为0,不占用空间,空结构体所创建的变量也不占用空间

#include <stdio.h>

struct TS
{

};

int main()
{
    struct TS t1;
    struct TS t2;

    printf("sizeof(struct TS) = %d\n", sizeof(struct TS));
    printf("sizeof(t1) = %d, &t1 = %p\n", sizeof(t1), &t1);
    printf("sizeof(t2) = %d, &t2 = %p\n", sizeof(t2), &t2);

    return 0;
}
结果1:Clion编译器
sizeof(struct TS) = 0
sizeof(t1) = 0, &t1 = 0x0093FF30
sizeof(t2) = 0, &t2 = 0x0093FF30
结果2:GCC编译器
sizeof(struct TS) = 0
sizeof(t1) = 0, &t1 = 0x7ffd7c56
sizeof(t2) = 0, &t2 = 0x7ffd7c57
结果3:VC编译器和BCC
error C2016: C 要求一个结构或联合至少有一个成员

可见不同编译器对空结构体的处理不同,一般认为是不允许空结构体存在,也没什么用,都有道理,



2、结构体与柔性数组(可变长数组)

这里写图片描述

3、柔性数组的用法

这里写图片描述
在申请大小空间时 一定要最后将数组的大小长度信息保存给len;
柔性数组 可以动态创建数组的大小;

#include <stdio.h>
#include <malloc.h>

struct SoftArray
{
    int len;
    int array[];
};

struct SoftArray* create_soft_array(int size)
{
    struct SoftArray* ret = NULL;

    if( size > 0 )
    {
        ret = (struct SoftArray*)malloc(sizeof(struct SoftArray) + sizeof(int) * size);

        ret->len = size;
    }

    return ret;
}

void delete_soft_array(struct SoftArray* sa)
{
    free(sa);
}

void func(struct SoftArray* sa)
{
    int i = 0;

    if( NULL != sa )
    {
        for(i=0; i<sa->len; i++)
        {
            sa->array[i] = i + 1;
        }
    } 
}

int main()
{
    int i = 0;
    struct SoftArray* sa = create_soft_array(10);

    func(sa);

    for(i=0; i<sa->len; i++)
    {
        printf("%d\n", sa->array[i]);
    }

    delete_soft_array(sa);

    return 0;
}
1
2
3
4
5
6
7
8
9
10
4、C语言中的union

这里写图片描述

5、union的注意事项

这里写图片描述

#include <stdio.h>

int system_mode()
{
    union SM
    {
        int i;
        char c;
    };

    union SM sm;

    sm.i = 1;

    return sm.c;
}


int main()
{
    printf("System Mode: %d\n", system_mode());
    return 0;
}
System Mode: 1
小端模式
6、小结

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值