C语言中的struct可以看做变量的集合:
问题:空结构体占多大内存?
#include<stdio.h>
struct TS
{
};
int main()
{
struct TS t1;
struct TS t2;
printf("sizeof(TS) = %d\n", sizeof(struct TS));
printf("sizeof(t1) = %d, &t1 = %p\n", sizeof(t1), &t1);
printf("sizeof(t1) = %d, &t2 = %p\n", sizeof(t2), &t2);
return 0;
}
在linux下使用Gcc进行编译运行:
sizeof(TS) = 0
sizeof(t1) = 0, &t1 = 0xbf963630
sizeof(t1) = 0, &t2 = 0xbf963630
但是在Bcc编译器下,会直接报错。//编译器认为,结构体的存在就是为了存放不同的数据类型。
结构体和柔性数组:
柔性数组即数组大小待定的数组;
C语言中可以由结构体产生柔性数组;
C语言中结构体的最后一个元素可以是大小未知的元素。
struct SoftArray
{
int len;
int array[]; -->> sizeof(struct SoftArray) = ???
}
SoftArray中的array[],仅仅是一个待使用的标识符,不占用存储空间。
printf("sizeof(struct SoftArray) = %d\n", sizeof(struct SoftArray));
sizeof(struct SoftArray) = 4
柔性数组的用法:
struct SoftArray sa* = NULL;
sa = (struc SoftArray*)malloc(sizeof(struct SoftArray) + sizeof(int)*5);
sa->len = 5; //带长度信息的数组,也就是说,可以使用柔性数组得到数组的长度信息。
sa->array; //动态申请的空间
观察下面代码,体会柔性数组的使用:
#include <stdio.h>
#include <malloc.h>
struct SoftArray
{
int len;
int array[];
};
struct SoftArray* creat_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 del_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 = creat_soft_array(10);
func(sa);
for(i=0; i<sa->len; i++)
{
printf("sa->array[] = %d\n", sa->array[i]);
}
del_soft_array(sa);
return 0;
}
C语言中的union:
union只分配最大成员的空间,所有成员共享这个空间。
union B
{
int a;
int b;
int c;
};
union的使用会受到系统大小端的影响:
小端: 低地址存储在低位
大端: 低地址存储在高位
union C
{
int i;
char c; //低地址上取数据
};
union C c;
c.i=1;
printf("%d\n", c.c); //?? 小端为1,大端为0;
利用这个特性,可以检测系统的大小端:
#include <stdio.h>
int system_mode()
{
union UN
{
int i;
char c;
};
union UN cn;
cn.i = 1;
return cn.c;
}
int main()
{
printf("%d\n", system_mode());
return 0;
}
小结:
struct中的每个数据成员都有独立的存储空间
struct可以通过最后的数组标识符产生柔性数组
union中的所有数组共享同一个存储空间
union的使用会受到系统大小端的影响