【C】10.struct 和 union 分析

struct 可以看做变量的集合

// 空结构体占用内存大小
struct ST
{};
sizeof("%d\n", sizeof(struct ST));

// gcc 环境编译下大小为0
// bcc 环境下大小为 1
//两款编译器理解不一样

#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);
		if(ret)
		{
			 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;
}

union用法与struct相识

只分配最大成员空间,所有成员共享这个空间(受大小端影响)

union c
{
  int i;
  char c;  
};
sizeif(union c);   // 4字节
// 判断电脑大小端模式的代码
union C
{
   int i;
   char c;
};
union C c;
c.i = 1;
printf("%d\n", C.c);

总结:

小端模式:低地址存放低位数据

大端模式:低地址存放高位数据

可通过程序判断系统是什么模式System_Mode

Union中所有的数据共用一个空间,同一时间只能存储其中一个数据成员,所有的数据成员具有相同的起始地址

 

注:本笔记是根据狄泰C课程做的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值