10_struct和union分析

本文深入探讨了C语言中的结构体(struct)和联合体(union),包括空结构体的内存占用、柔性数组的使用,以及union与struct的区别。通过代码实践,展示了如何创建和操作柔性数组,并利用union判断系统的大端或小端特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

输出结果为:
在这里插入图片描述
在gcc编译器中,空结构体大小为0

2、结构体与柔性数组

  • 柔性数组即大小待定的数组
  • C语言中可以由结构体产生柔性数组
  • C语言中结构体的最后一个元素可以是大小未知的数组
    在这里插入图片描述
    柔性数组的用法
    在这里插入图片描述
    代码实践:
#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;
}

输出结果为:
在这里插入图片描述

3、union与struct的区别

#include <stdio.h>

struct my_struct
{
    int a;
    int b;
    int c;
};

union my_union
{
    int a;
    int b;
    int c;
};

int main(void)
{
    printf("sizeof(struct my_struct) = %d\n",sizeof(struct my_struct));
    printf("sizeof(union my_union) = %d\n",sizeof(union my_union));    

    return 0;
}

输出结果为:
在这里插入图片描述

4、用union来判断大小端

#include <stdio.h>

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

    union SM sm;

    sm.i = 1;

    return sm.c;
}


int main()
{
    if(system_mode() == 1)
    {
        printf("little\n");
    }
    else
    {
        printf("big\n");
    }
    return 0;
}

5、小结

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值