c语言深度剖析(10)—struct和union分析

1.struct的小秘密

  • C语言中的struct可以看作变量的集合
  • struct的问题:空结构体占用多大内存?
#include <stdio.h>

struct TS
{

};

int main()
{
    struct TS t1;
    struct TS t2;
    
    // VC、BCC下定义空结构体编译器直接报错,gcc下空结构体大小为0
    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;
}

2.结构体与柔性数组

  • 柔性数组数组大小待定的数组
  • C语言中可以由结构体产生柔性数组
  • C语言中结构体的最后一个元素可以是大小未知的数组
struct SoftArray
{
  int len;
  int array[]; // array仅是一个待使用的标识符。与指针不同,编译器
               // 并不为array变量分配空间,因为也不知道array究竟
               // 多大。只是用来作为一个标识符,以便以后可以通过这
               // 个标识符来访问其中的内容。所以sizeof(SoftArray)=4
}
  • 柔性数组的用法

struct SoftArray *sa = NULL;
 // 注意,因sizeof柔性数组并不包含array大小,所以要开辟的空间总大小应等于
 // 柔性数组+数组各元素所占的空间,即空间大小等于结构体的大小(len域)加上数组的大小
 sa = (struct SoftArray *)malloc(sizeof(struct SoftArray)+sizoef(int)*5);
 sa->len = 5;

3.编程实验

  • 柔性数组使用分析
#include <stdio.h>
#include <stdlib.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);

	system("pause");
	
	return 0;
}

4. C语言中的union

  • C语言中的union在语法上与struct相似
  • union只分配最大成员的空间所有成员共享这个空间

  • union的使用受系统大小端的影响

5.编程实验

  • 判断系统的大小端  
#include <stdio.h>
#include <stdlib.h>

int system_mode()
{
	union SM
	{
		int i;
		char c;  // 变量i和c有相同起始地址
	};

	union SM sm;

	sm.i = 1;

	return sm.c;  // 相当于返回首字节
}

int main()
{
	// 返回1时为小端,0为大端模式
	printf("System Mode: %d\n", system_mode());
	
	system("pause");
	
	return 0;
}

6. 小结

  • struct中的每人数据成员有独立的存储空间
  • struct可以通过最后的数组标识符产生柔性数组
  • union中的所有数据成员共享同一个存储空间
  • union的使用会受到系统大小端的影响
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值