本节实验了空结构体大小,介绍了柔性数组
1、struct的小秘密
C语言中的 struct 可以看作变量的集合
struct 的问题:空结构体占用多大内存?
2、实例分析
空结构体的大小 test.c
#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(不同版本)
BCC(标准C)
VS2010
C语言灰色地带,观点没有谁对谁错,C++的空strcut参考:直达
3、结构体与柔性数组
柔性数组即数组大小待定的数组
C语言中可以由结构体产生柔性数组
C语言中结构体的最后一个元素可以是大小未知的数组
柔性数组的用法
4、实例分析
柔性数组使用分析 10-2.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;
}
5、C语言中的union
C语言的union在语法上与struct相似
union只是分配最大成员的空间,所有成员共享这个空间
6、union的注意事项
union的使用受系统大小端的影响
7、编程实验
判断系统的大小端 test.c
#include <stdio.h>
int system_mode()
{
union SM
{
int i;
char c; //变量i和c有相同起始地址
};
union SM sm;
sm.i = 1;
return sm.c; //相当于返回首字节
}
int main()
{
printf("System Mode: %d\n", system_mode()); //若为1说明数据存放在低位,小端存储
return 0;
}
8、小结
struct中每个数据成员有独立的存储空间
struct可以通过最后的数组标识符产生柔性数组
union中所有数据成员共享同一个内存空间
union的使用会受到系统大小端的影响
9、扩展
位域的简单介绍
位域是指信息在存储时,并不需要占用一个完整的字节, 而只需占几个或一个二进制位。例如在存放一个开关量时,只有0和1 两种状态, 用一位二进位即可。为了节省存储空间,并使处理简便,C语言又提供了一种数据结构,称为“位域”或“位段”。所谓“位域”是把一个字节中的二进位划分为几 个不同的区域, 并说明每个区域的位数。每个域有一个域名,允许在程序中按域名进行操作。 这样就可以把几个不同的对象用一个字节的二进制位域来表示。- 百度百科
位域的好处
union Test
{
struct
{
unsigned char a : 2;
unsigned char b : 2;
unsigned char c : 2;
unsigned char d : 2;
}c1;
unsigned char c2;
};