--事物的难度远远低于对事物的恐惧!
大家好,今天来看看C语言中的struct与union,我们都知道,C语言中的struct可以看作变量的集合。那么首先来抛出一个问题:空结构体所占的内存空间为多大?
答案是不同的编译器结果不同,在gcc中,空结构体占0个字节;而在vs2010中直接编译不过。
结构体与柔性数组
-柔性数组即数组的大小待定的数组
-C语言中可以由结构体产生柔性数组
-C语言中结构体的最后一个元素可以是大小未知的数组
struct SoftArray
{
int len;
int array[];
}
sizeof(struct SoftArray) = ? //该语句输出多少?
注意:SoftArray中的array仅仅是一个待使用的标识符,不占用存储空间!
那么我们该怎么去使用柔性数组呢?请看下图:
下边来看个具体的代码
#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 ", sa->array[i]);
}
printf("\n");
delete_soft_array(sa); //销毁柔性数组
return 0;
}
输出如下:
说完了struct,现在来说说union,union中只分配最大成员的空间,所有成员共享这个空间。
同时比较重要的一点是,union的使用受系统大小端的影响
请思考下边这段代码:
union C
{
int i;
char c;
};
union C c;
c.i = 1;
printf("%d\n", c.c); //输出多少?
我的电脑上vs2010输出如下:(说明我的系统为小端模式,如果在大端模式的系统中,则输出0)
总结:
1、struct中的每个数据成员都有独立的存储空间
2、struct可以通过最后的数组标识符产生柔性数组
3、union成员共享同一个存储空间,空间大小与最大成员所占空间大小一致
4、union的使用会受到系统大小端的影响