·C语言中的struct可以看做变量的集合
不同类型的变量放在一起同时使用
例子10-1:
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\n", sizeof(t1));printf("sizeof(t1) = %d\n", sizeof(t2));return 0;
}
输出结果:
error;代码中不允许出现空结构体
空结构体占用的内存为0;
结构体与柔性数组
·柔性数组即数组大小待定的数组
·C语言中可以由结构体产生柔性数组
·C语言中结构体的最后一个元素可以是大小未知的数组
例子10-1-1:
include "stdio.h"
struct soft_array
{
int len;int array[];
};
int main()
{
printf("sizeof(struct soft_array) = %d\n", sizeof(struct soft_array));return 0;
}
输出结果:
sizeof(struct soft_array) = 4
int array[]在代码中不占用内存,只是一个标识。
柔性数组使用分析例子10-2:
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 (sa != NULL){ 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]);}
}
输出结果:
1
2
3
4
5
6
7
8
9
10
C语言中的union
·C语言中的union在语法上与struct相似
·union只分配最大成员的空间,所有成员共享这个空间
·union的使用受系统大小端的影响
小端模式:占用系统的低位
大端模式:占用系统的高位
判断系统的大小端 例子10-3.c
include"stdio.h"
int system_mode()
{
typedef union { int a; char b;}TS;TS sm;sm.a = 1;return sm.b;
}
int main()
{
printf("system_mode:%d\n", system_mode());return 0;
}
输出结果:
system_mode:1
小结:
·struct中的每个数据成员都有独立的空间
·struct可以通过最后的数组标识符产生柔性数组
·union中的所有数据成员共享同一个存储空间
·union是使用会受到系统大小端的影响